Every time I try to display the category I get the name Array instead of the category name. I was wondering how can I display the category names from my code below?
$list = array();
$cat = array();
$query = mysqli_query($dbc,"SELECT id, parent_id, category FROM categories ORDER BY parent_id, category LIKE category ASC");
while($row = mysqli_fetch_assoc($query)){
$list[$row['id']] = array_merge($row, array('children' => array()));
}
mysqli_free_result($query);
foreach($list as $nodeId => &$node) {
if(!$node['parent_id'] || !array_key_exists($node['parent_id'], $list)){
$cat[] = &$node;
} else {
$list[$node['parent_id']]['children'][] = &$node;
}
}
unset($node);
unset($list);
Var dump output example.
array
0 => &
array
'id' => string '1' (length=1)
'parent_id' => string '0' (length=1)
'category' => string 'Cat-1' (length=5)
'children' =>
array
0 => &
array
...
1 => &
array
...
2 => &
array
...
When you echo a variable, and the browser display’s “Array”, you need to go another level deeper to access the array elements. You may have tried this already, but
var_dump()your category array to view the structure of your array and verify it is what you expected it to be. YOu will be able to analyze your apparent multi-dimensional array to judge how many loops you need to get to the category names.Update:
to go a level deeper, you need nested loops. for example: