Home >Backend Development >PHP Tutorial >数组对比效率问题
两个数组,ArrayA和ArrayB
$arrayA = array ( 0 => array ( 0 => 1, 4 => 1, 6 => 1, ), 1 => array ( 1 => 1, 3 => 1, 5 => 1, ), 2 => array ( 7 => 1, 8 => 1, 9 => 1, ), );
$arrayB = array ( 0 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), 1 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), 2 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), );
希望得到结果
$result = array ( 0 => array ( 0 => 'a', 4 => 'e', 6 => 'g', ), 1 => array ( 1 => 'b', 3 => 'd', 5 => 'f', ), 2 => array ( 7 => 'h', 8 => 'i', 9 => 'j', ), );
我现在的做法是做两层循环
$result = array (); foreach ($arrayA as $k => $v) { foreach ($v as $kk => $vv) { $result[$k][$kk] = $arrayB[$k][$kk]; } }
有没有什么效率更高的方式呢?
两个数组,ArrayA和ArrayB
$arrayA = array ( 0 => array ( 0 => 1, 4 => 1, 6 => 1, ), 1 => array ( 1 => 1, 3 => 1, 5 => 1, ), 2 => array ( 7 => 1, 8 => 1, 9 => 1, ), );
$arrayB = array ( 0 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), 1 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), 2 => array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', ), );
希望得到结果
$result = array ( 0 => array ( 0 => 'a', 4 => 'e', 6 => 'g', ), 1 => array ( 1 => 'b', 3 => 'd', 5 => 'f', ), 2 => array ( 7 => 'h', 8 => 'i', 9 => 'j', ), );
我现在的做法是做两层循环
$result = array (); foreach ($arrayA as $k => $v) { foreach ($v as $kk => $vv) { $result[$k][$kk] = $arrayB[$k][$kk]; } }
有没有什么效率更高的方式呢?
使用 PHP 的内置函数 array_intersect
即可
参考