Reputation: 293
I would like some guidance with regards to how to display data in an array that may or may not be multi-dimensional.
I currently use this -
if (count($array) == count($array, COUNT_RECURSIVE)){
echo $array['Name'];
echo $array['Surname'];
echo $array['Email'];
}else{
foreach($res as $val){
echo $val['Name'];
echo $val['Surname'];
echo $val['Email'];
}
}
This work ok, however, it does mean a lot of duplicate code if there are multiple fields to display.
Is there a way to condense the code so there is no duplication?
Upvotes: -1
Views: 111
Reputation: 306
Easier way could be using array_walk_recursive function. In php manual you will have the example also.
Upvotes: 0
Reputation: 173662
The easiest would arguably be to modify the array when necessary:
if (count($array) == count($array, COUNT_RECURSIVE)) {
$array = array($array);
}
foreach($res as $val){
echo $val['Name'];
echo $val['Surname'];
echo $val['Email'];
}
Upvotes: 1
Reputation: 3434
You need to use an recursive function for this. Here is an example of an recursive function which echo's the elements in a multidimensional array:
$array = array(
array("a", array("a","b","c"),"c"=>"c"),
array("a","b","c"),
array("a","b","c"));
displayArray($array);
function displayArray($array)
{
foreach($array as $k => $v)
{
if(is_array($v))
{
displayArray($v);
}
else
{
echo $v."<br />";
}
}
}
The output will be:
aabccabcabc
Upvotes: 0