2015-05-04 130 views
2

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

$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功能做到这一点。

+2

你试过吗? –

回答

2
$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_walk_recursive($sample, function($a) use (&$return) { $return[] = $a; }); 

var_dump($return); 

输出:

array(6) { [0]=> string(8) "Nokia 72" [1]=> string(10) "Samsung 58" [2]=> string(10) "Samsung 64" [3]=> string(14) "Micromax 1542c" [4]=> string(5) "LG 58" [5]=> string(5) "LG 64" } 

这里是一个PHP沙箱与演示:http://sandbox.onlinephpfunctions.com/

此解决方案使用array_walk_recursive()和PHP匿名函数。

http://php.net/array_walk_recursive

http://php.net/manual/en/functions.anonymous.php

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>'; 
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)