-1

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?

3
  • write a function to display array data Commented Nov 27, 2014 at 4:25
  • Use a recursive iterator function. You are basically halfway there with what you have. Look up either how to manually do a recursive function or use the OOP iterator classes Commented Nov 27, 2014 at 4:29
  • Is this your real code? As in, are you really just outputting the fields and nothing else? Commented Nov 27, 2014 at 4:41

3 Answers 3

1

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Easier way could be using array_walk_recursive function. In php manual you will have the example also.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.