数组对比效率问题

WBOY
WBOYasal
2016-06-06 20:51:09982semak imbas

两个数组,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 即可

参考

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn