简体   繁体   中英

PHP iterating through arrays

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?

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'];
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM