array(2) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["name"]=>
string(3) "Lim"
["subproject_id"]=>
string(1) "5"
["subproject_name"]=>
string(4) "Mads"
}
[1]=>
array(1) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["name"]=>
string(3) "Lim"
["subproject_id"]=>
string(1) "4"
["subproject_name"]=>
string(5) "KANYE"
}
}
}
How can I output each name
and subproject_name
?
A simple foreach()
will only get the first one.
Try this:
array_walk_recursive($array, function($item, $key) {
if (in_array($key, array('name', 'subproject_name'))) {
echo $item;
}
});
See http://php.net/manual/en/function.array-walk-recursive.php
Note: for PHP 5.3.0 you can use callback, in earlier versions you need non-anonymous function.
Consult the php documentation, look for "array_walk" and "array_walk_recursive".
Don't know how much that array could vary, but here is one simple solution.
foreach($array as $key => $value){
if(!isset($value['id']))
$value = $value[0];
echo $value['name'];
echo $value['subproject_name'];
}
if its getting deeper, you can use 'while' instead of 'if'.
With array_walk_recursive:
function print_info ($item, $key) {
if (strcmp ($key, "name") == 0)
echo "name = {$item}<br>";
if (strcmp ($key, "subproject_name") == 0)
echo "subproject_name = {$item}<br>";
}
array_walk_recursive($array, 'print_info');