在PHP中组合这些数组的最有效方法是什么?

时间:2011-12-22 19:47:29

标签: php arrays

我正在尝试获取两个数组(我认为这意味着它们是多维的)通过共享值组合/合并在一起。换句话说,类似于SQL中的JOIN语句。有没有一种特定的,有效的方法来解决这个问题?

尝试合并这两者:

Array
(
    [0] => Array
        (
            [0] => 5
            [1] => alice
            [2] => car
        )

    [1] => Array
        (
            [0] => 3
            [1] => bob
            [2] => truck
        )

    [2] => Array
        (
            [0] => 5
            [1] => charlie
            [2] => bike
        )

)
Array
(
    [0] => Array
        (
            [0] => 5
            [1] => alice
            [2] => Vancouver
        )

    [1] => Array
        (
            [0] => 3
            [1] => bob
            [2] => Toronto
        )

    [2] => Array
        (
            [0] => 5
            [1] => charlie
            [2] => Portland
        )

)

生产:

Array
(
    [0] => Array
        (
            [0] => 5
            [1] => alice
            [2] => car
            [3] => Vancouver
        )

    [1] => Array
        (
            [0] => 3
            [1] => bob
            [2] => truck
            [3] => Toronto
        )

    [2] => Array
        (
            [0] => 5
            [1] => charlie
            [2] => bike
            [3] => Portland
        )

)

2 个答案:

答案 0 :(得分:2)

foreach ($a as $key => $val) {
    $result[$key] = array_unique(array_merge($a[$key], $b[$key]));
}

我选择这样的事情。首先合并两个数组,然后整理重复的项目。这当然要求两个数组都具有相同的长度和数字标记。

答案 1 :(得分:0)

“最佳”你首先不会有两个数组。

特定案例的解决方案:

$a1 = [
  [5, 'alice', 'car'],
  [3, 'bob', 'truck'],
  [5, 'charlie', 'bike'],
];

$a2 = [
  [5, 'alice', 'Vancouver'],
  [3, 'bob', 'Toronto'],
  [5, 'charlie', 'Portland']
];

$a3 = array_map(function($a, $b) { $a[] = $b[2]; return $a; }, $a1, $a2);

结果(部分):

array(3) {
  [0] =>
  array(4) {
    [0] =>
    int(5)
    [1] =>
    string(5) "alice"
    [2] =>
    string(3) "car"
    [3] =>
    string(9) "Vancouver"
  }
...

如果您不需要保留$a1,那么您真的不会得到比以下更好的解决方案:

foreach ($a1 as $key => $val)
  $a1[$key][] = $a2[$key][2];