如何从复杂的多维数组中获取所有值?

时间:2015-05-04 11:12:36

标签: php arrays multidimensional-array

我有以下多维数组

$sample = array(
        '1232' => 'Nokia 72',
        '234' => array(
                    '534' => 'Samsung 58',
                    '345' => 'Samsung 64'
                  ),
        '3445' => 'Micromax 1542c',
        '542' => array(
                    '4645' => 'LG 58',
                    '5765' => 'LG 64'
                  )
      );

现在,我想只收集每个部分的每个值的值。

我的输出应该如下

 
 Array 
 ( 
  [0] => Nokia 72
  [1] => Samsung 58
  [2] => Samsung 64
  [3] => Micromax 1542c
  [4] => LG 58
  [5] => LG 64
 ) 
 

我不想用foreach函数来做。

3 个答案:

答案 0 :(得分:2)

您可以使用

来完成



array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output); 




您还可以从以下链接获得更多参考资料

How-to-filter-only-values-from-complex-multi-dimensional-array

答案 1 :(得分:1)

RecursiveIteratorIterator 当您使用iterator_to_array函数时,它会返回一个展平的数组。

Demo

$sample = array(
        '1232' => 'Nokia 72',
        '234' => array(
                    '534' => 'Samsung 58',
                    '345' => 'Samsung 64'
                  ),
        '3445' => 'Micromax 1542c',
        '542' => array(
                    '4645' => 'LG 58',
                    '5765' => 'LG 64'
                  )
      );

$it =  new RecursiveIteratorIterator(new RecursiveArrayIterator($sample));
$l = iterator_to_array($it, false);
echo '<pre>';print_r($l);echo '</pre>';

答案 2 :(得分:0)

如果你想用递归函数自己实现它:

$sample = array(
        '1232' => 'Nokia 72',
        '234' => array(
            '534' => 'Samsung 58',
            '345' => 'Samsung 64'
            ),
        '3445' => 'Micromax 1542c',
        '542' => array(
            '4645' => 'LG 58',
            '5765' => 'LG 64'
            )
        );

// This recursive function changes the original values!
function walk(&$multi_dim_array, &$flat_array)
{
    while (sizeof($multi_dim_array) > 0)
    {
        // Take the first element
        $curr_value = array_shift($multi_dim_array);
        // If this item is an array go one step deeper
        if (is_array($curr_value))
            walk($curr_value, $flat_array);
        else
            // The current value is not an array
            // append it to the flattened array
            $flat_array[] = $curr_value;
    }
}

$values = [];
walk($sample, $values);
print_r($values);

输出

Array ( [0] => Nokia 72 [1] => Samsung 58 [2] => Samsung 64 [3] => Micromax 1542c [4] => LG 58 [5] => LG 64 )