hi everybody have a good day . i have an question regarding to echo value form mysql database Now i have a table name ---> materialachievement
Inside the table i have 3 column (chapter ,subchapter and part)
the data is like below:
chapter subchapter part
-------------------------------------
2 2.1 1
2 2.1 2
2 2.1 3
2 2.2 1
2 2.2 2
3 3.1 1
3 3.1 1
-------------------------------------
Now i want do a table to echo chapter 2 and 3 and inside chapter 2 has subchapter 2.1 and subchapter 2.2 inside subchapter 2.1 has part 1 , 2 , 3 and inside subchapter 2.2 has part 1 , 2
the structure is like :
2
2.1
1
2
3
2.2
1
2
So my question is how can i just echo chapter 2 for once , then subchapter 2.1 for once , then go to part 1 , 2 , 3 ? same with sunchapter 2.2.
$query="SELECT * FROM materialachievement WHERE sID=$id GROUP BY (chapter and subchapter) ORDER BY chapter ASC , subchapter ASC ";
$result=mysql_query($query,$conn);
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result))
{
$chapter = $row['chapter'];
$subchapter = $row['subchapter'];
echo "<br>Chapter :".$chapter."<br>";
echo "<br>Subchapter :".$subchapter."<br>";
}
now the result suppose be : chapter 2 , subchapter 2.1 , subchapter 2.2 , subchapter 2.3 and chapter 3 , subchapter 3.1 , subchapter 3.2
$query="SELECT * FROM materialachievement WHERE sID=$id ORDER BY chapter ASC, subchapter ASC, part ASC ";
$result=mysql_query($query,$conn);
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
$last_chapter = null;
while($row=mysql_fetch_array($result))
{
$chapter = $row['chapter'];
$subchapter = $row['subchapter'];
$part = $row['part'];
if ($last_chapter !=== $chapter) {
echo "Chapter: $chapter<br>";
$last_chapter = $chapter;
$last_subchapter = null;
}
if ($subchapter !== $last_subchapter) {
echo "Subchapter: $subchapter<br>";
$last_subchapter = $subchapter;
}
echo "Part: $part<br>";
}
hope this help
$data=array();
$data[] = array("chapter" => "2", "subchapter" => "2.1", "part" => "1" );
$data[] = array("chapter" => "2", "subchapter" => "2.1", "part" => "2" );
$data[] = array("chapter" => "2", "subchapter" => "2.1", "part" => "3" );
$data[] = array("chapter" => "2", "subchapter" => "2.2", "part" => "1" );
$data[] = array("chapter" => "2", "subchapter" => "2.2", "part" => "2" );
$data[] = array("chapter" => "3", "subchapter" => "3.1", "part" => "1" );
$data[] = array("chapter" => "3", "subchapter" => "3.1", "part" => "1" );
$new_array=array();
foreach($data AS $v){
if(!array_key_exists($v['chapter'],$new_array )){
$new_array[$v['chapter']]=array();
}
if(!array_key_exists($v['subchapter'],$new_array[$v['chapter']]) ){
$new_array[$v['chapter']][$v['subchapter']]=array();
}
$new_array[$v['chapter']][$v['subchapter']]=$v['part'];
}
print_r($new_array);
output
Array
(
[2] => Array
(
[2.1] => 3
[2.2] => 2
)
[3] => Array
(
[3.1] => 1
)
)