1

これは基本的なループの質問ですが、ひねりが加えられているため、簡単なものが欠けている可能性があります-事前にお詫びします...

配列$testoutputから結果を取得しようとしています-3つの配列で埋められています:

次のコードを実行します。

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

戻り値:

ARRAY
ARRAY
ARRAY

次のコードで2番目のネストされたループを追加します。

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レベルから値を返す方法がわかりません。

これを行う簡単な方法はありますか?

よろしくお願いします。

4

3 に答える 3

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');
于 2010-10-22T01:48:45.510 に答える
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);
于 2010-10-22T02:15:45.850 に答える
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;
      }
   }
}
于 2010-10-22T09:50:18.317 に答える