Home >Backend Development >PHP Tutorial >数组对比效率问题

数组对比效率问题

WBOY
WBOYOriginal
2016-06-06 20:51:09977browse

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

参考

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn