Reputation:
I have a multidimensional array and I was given a foreach loop, but don't know how to echo out all the values without using print_r. I do get a result if I echo $array[0][0];
outside the foreach loop, for the first result.
I had seen other examples but nothing to show the results other than print_r and they tend to do only a single array, not a multidimensional array.
I had seen this foreach loop that seems like it would work, but I only get errors if I try to do echo $new_array
inside the foreach loop. How can I use this for something like this situation?
foreach($array as $key=>$val) {
$new_array[] = $val['key'];
}
array results from print_r
[0] => Array
(
[0] => 2
[audit_inspectionID] => 10
[1] => 2015-08-12
[created] => 2015-08-12
[2] => 2016-08-11 16:26:22
[modified] => 2016-08-11 16:26:22
[class_answer] => Array
(
[0] => Needs Improvement
[1] => Need To Correct
[2] => Needs Immediate Action
)
)
[1] => Array
(
[0] => 12
[audit_inspectionID] => 12
[1] => 2016-08-12
[created] => 2016-08-12
[2] => 2016-08-11 16:26:22
[modified] => 2016-08-11 16:26:22
[class_answer] => Array
(
[0] => Needs Improvement
[1] => Need To Correct
[2] => Needs Immediate Action
)
)
Upvotes: 1
Views: 702
Reputation: 2481
I'm not really sure what you're asking, but if you want something which will print out all of the keys and values (In what format? You don't specify) regardless of arrays nested inside each other you could do something like:
function arrayToString(array $array)
{
$out = "";
foreach ($array as $key => $value) {
if (is_array($value)) {
$out .= "$key => (" . arrayToString($value) . "), ";
} else {
$out .= "$key => $value, ";
}
}
return $out;
}
The you can echo arrayToString($myArray)
where $myArray
is the array you want to echo - it'll leave trailing commas but I'm sure you can modify it to do what you need it to, this should give you an idea of how to go about it.
Is that the sort of thing you wanted? I don't really see the point of this but hopefully this helps you out.
Upvotes: 0