Peka Chawngthu Peka Chawngthu - 1 month ago 7
PHP Question

How to correctly print the repeated rows?

I have simulated the mysql result from an old SO question as the following array:

<?php
$arr = array(
array(
'title'=>'Test',
'name'=>'ABC',
'cat_desc'=>'ABC_DESC',
'parent'=>0,
'parent_menu'=>1
),
array(
'title'=>'Test2',
'name'=>'DEF',
'cat_desc'=>'DEF_DESC',
'parent'=>0,
'parent_menu'=>2
),
array(
'title'=>'Test2',
'name'=>'GHI',
'cat_desc'=>'GHI_DESC',
'parent'=>1,
'parent_menu'=>0
),
array(
'title'=>null,
'name'=>'JKL',
'cat_desc'=>'JKL_DESC',
'parent'=>2,
'parent_menu'=>0
)
);
//print_r($arr);
?>


Now I wonder if I could print the result in this format:

<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>

<tr>
<td> Menu Title Test </td>
<td> Main Category ABC</td>
</tr>
<tr>
<td>GHI</td>
<td>GHI_DESC</td>
</tr>
<tr>
<td> Menu Title Test2 </td>
<td> Main Category DEF</td>
</tr>
<tr>
<td>JKL</td>
<td>JKL_DESC</td>
</tr>
</table>


I am trying the following php to print but it could not give the expected result:

<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php
$r = 0;
while(list($key, $val)=each($arr)) {
if($val['parent']==0):
if($r % 1==0): ?>
<tr>
<td> Menu Title <?php echo $val['title'];?> </td>
<td> Main Category <?php echo $val['name'];?></td>
</tr>
<?php endif;
endif;
if($val['parent']!=0){ ?>
<tr>
<td><?php echo $val['name'];?></td>
<td><?php echo $val['cat_desc'];?></td>
</tr>
<?php
}
$r++;
} ?>
</table>


Your help and suggestion is very much welcome.

jfk jfk
Answer

I find it difficult to figure out what you exactly want from your array structure. But I noticed that array element 0 is paired with element 2, and element 1 is paired with element 3. Therefore my code would be like following. It will give you exactly the table that you wanted.

print "<table border=1>";

$numArray = count($arr) / 2;

for($i=0;$i<$numArray;$i++) {
    $element = $arr[$i];
    print "<tr><td>Menu Title {$element['title']}</td><td>Main Category {$element['name']}</td></tr>";
    $element = $arr[$i+2];
    print "<tr><td>{$element['name']}</td><td>{$element['cat_desc']} </td></tr>";
}

print "</table>";