PHP - 将某些数组从多维数组复制到另一个新数组

时间:2014-01-26 14:59:21

标签: arrays multidimensional-array copy

我有这个数组:

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => c [1] => a [2] => d [3] => [4] => ) 

[2] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

[3] => Array ( [0] => a [1] => d [2] => c [3] =>b [4] => )

)

并且想知道我是否可以将所有内部数组从它复制到第一个元素为“b”的另一个数组,所以它看起来像。新数组在创建时是否会重新编制索引?谢谢。

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

)

2 个答案:

答案 0 :(得分:3)

更新:我的代码中出现了一点错误。现在,如果您仍然需要它,它将被修复并正常工作。

$firstArray = array (array ('b', 'd', 'c', 'a'), 
                     array ('c', 'd', 'a', 'b'), 
                     array ('b', 'd', 'a', 'c'), 
                     array ('a', 'd', 'c', 'b'));

$secondArray = array();

foreach($firstArray as $sub) {

    if($sub[0] == 'b') {

        $secondArray[] = $sub;
    }
}

print_r($secondArray);

输出:

Array ( [0] => Array ( [0] => b [1] => d [2] => c [3] => a ) 
        [1] => Array ( [0] => b [1] => d [2] => a [3] => c ) )

答案 1 :(得分:2)

function check($val) {
     return ($val[0] == 'b');
}
$secondArray = array_filter($firstArray, "check");