Echo a multidimensional array in PHP

后端 未结 9 1579
名媛妹妹
名媛妹妹 2020-11-27 07:24

I have a multidimensional array and I\'m trying to find out how to simply \"echo\" the elements of the array. The depth of the array is not known, so it could be deeply nest

9条回答
  •  失恋的感觉
    2020-11-27 08:10

    Proper, Better, and Clean Solution:

    function traverseArray($array)
    {
        // Loops through each element. If element again is array, function is recalled. If not, result is echoed.
        foreach ($array as $key => $value)
        {
            if (is_array($value))
            {
                Self::traverseArray($value); // Or
                // traverseArray($value);
            }
            else
            {
                echo $key . " = " . $value . "
    \n"; } } }

    You simply call in this helper function traverseArray($array) in your current/main class like this:

    $this->traverseArray($dataArray); // Or
    // traverseArray($dataArray);
    

    source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/

提交回复
热议问题