首頁  >  文章  >  後端開發  >  数组对比效率问题

数组对比效率问题

WBOY
WBOY原創
2016-06-06 20:51:09951瀏覽

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

参考

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn