PHP通过一个包含字符串和内部数组的数组循环

时间:2010-10-22 01:45:35

标签: php arrays loops nested-loops

这是一个基本的循环问题,但有一个扭曲,所以很可能我错过了一些简单的事情 - 事先道歉......

我正在尝试从数组$ testoutput中提取结果 - 该数组填充了3个数组:

运行以下代码:

foreach ($testoutput as $ID => $Array) {
   echo $Array . "<BR>";
}

返回:

ARRAY
ARRAY
ARRAY

使用以下代码添加第二个嵌套循环:

foreach ($testoutput as $ID => $Array) {
   foreach ($Array as $ID => $L1item) {
      echo $L1item . "<BR>";
   }
}

结果:

String1a
String1b
String1c
ARRAY
String2a
String2b
String2c
ARRAY
String3a
String3b
String3c
ARRAY

我很好地重新调整了所有上面的字符串,但是,我无法弄清楚如何从嵌套数组的第3级返回值。

有一种简单的方法吗?

非常感谢提前。

3 个答案:

答案 0 :(得分:2)

您可以使用array_map

$testoutput = array('x', array('y', 'z', array('1', '2', '3')));
function output($element) {
    if(is_array($element)) {
       array_map('output', $element); //RECURSION
       return;
    }
    echo $element;
}
array_map('output', $testoutput);   

或者,如果您愿意,可以使用array_walk_recursive

function output(&$value, $index) {
    echo $value;
}
array_walk_recursive($testoutput, 'output');

答案 1 :(得分:0)

试试这个:

/** 
 * array nested_array_map(callback $callback, array $array)
 * Warning - doesn't check for recursion, 
 *           therefore child arrays shouldn't contain references to any of parent level arrays
 *
 * @param $callback, function
 * @param $array, array of elements to map the function to
 * @return array
 */
function nested_array_map($callback, $param) {
    if (!is_array($param)) {
        return call_user_func($callback, $param);
    }

    $result = array();
    foreach ($param as $index => $value) {
        $result[$index] = nested_array_map($callback, $value);
    }
    return $result;
}

function echo_value($value) {
    echo "$value\n";
    return $value;
}

$test = array(
    '1st level'
    ,array(
        '2nd level'
        ,array(
            '3rd level'
        )
        ,'2nd level'
    )
    ,array(
        '2nd level'
    )
    ,'1st level'
);

$result = nested_array_map('echo_value', $test);

答案 2 :(得分:0)

foreach ($testoutput as $key1 => $value1) {
   foreach ($value1 as $key2 => $value2) {
      if(is_array($value2))
      {
              foreach ($value2 as $key3 => $value3) {
                          echo $value3;
              }
      }
      else
      {
              echo $value2;
      }
   }
}
相关问题