php基于2个子键合并多重组合阵列

时间:2012-06-11 11:23:48

标签: php multidimensional-array

我有2个数组,并希望将它们合并在一起,并且在第二个数组中找不到项,插入一个空值的键。 基本上从array1中的array2添加匹配2个array1子项的项目; Array2的长度不必与数组1的长度相同,它的长度也很小。

ARRAY1

[0][item] = 'aaaa'
   [type] = '1234'

[1][item] = 'aaaa'
   [type] = '6789'

[2][item] = 'bbbb'
   [type] = '1234'

[3][item] = 'bbbb'
   [type] = '6789'

和array2:

[0][item] = 'aaaa'
   [type] = '1234'
   [feature] = 'www'

[1][item] = 'aaaa'
   [type] = '6789'
   [feature] = 'www'

结果:

[0][item] = 'aaaa'
   [type] = '1234'
   [feature] = 'www'

[1][item] = 'aaaa'
   [type] = '6789'
   [feature] = 'www'

[2][item] = 'bbbb'
   [type] = '1234'
   [feature] = ''

[3][item] = 'bbbb'
   [type] = '6789'
   [feature] = ''

我在这里尝试了几个建议,它们都归结为一个二维数组或匹配索引。任何sugestions?

4 个答案:

答案 0 :(得分:0)

你尝试过这样的事吗?

foreach ($array1 as $key=>$value){
   if (isset($array2[$key]['feature'])){
      $array1[$key]['feature'] = $array2[$key]['feature'];
   } else {
      $array1[$key]['feature'] = '';
   }
}

答案 1 :(得分:0)

让PHP通过数组键为您进行匹配:

$result=array();
foreach ($array1 as $item) {
  $item['feature']='';
  $result[$item['item'].'-'.$item['type']]=$item;
}
foreach ($array2 as $item) {
  $result[$item['item'].'-'.$item['type']]['feature']=$item['feature'];
}
$result=array_values($result);

答案 2 :(得分:0)

你可以使用这样的东西:

array_walk($array, function ($arr, $key) use ($array2) {
   if (array_key_exists($key, $array2) && is_array($array2[$key])) {
      $arr = array_merge($arr, $array2[$key]);
   }
});
print_r($array); // Will have all missed keys from $array2

答案 3 :(得分:0)

“feature”不需要空字符串,在以后的迭代中,您可以使用isset进行检查。保持简单,不要创建您不需要或难以维护的结构。这适用于n个子键,无需维护。

$ar1 = array(
        array('item' => 'aaaa', 'type' => '1234'),
        array('item' => 'aaaa', 'type' => '6789'),
        array('item' => 'bbbb', 'type' => '1234'),
        array('item' => 'bbbb', 'type' => '6789')
    );
    $ar2 = array(
        array('item' => 'aaaa', 'type' => '1234','feature' => 'www'),
        array('item' => 'aaaa', 'type' => '6789','feature' => 'www')
    );
    for ($i = 0;$i<count($ar1);$i++) {
        if (array_key_exists($i, $ar2)){
            $result[] = array_merge($ar2[$i], $ar1[$i]);
        } else {
            $result[] = $ar1[$i];
        }
    }

// result
Array
(
    [0] => Array
        (
        [item] => aaaa
        [type] => 1234
        [feature] => www
    )

    [1] => Array
    (
        [item] => aaaa
        [type] => 6789
        [feature] => www
    )

    [2] => Array
    (
        [item] => bbbb
        [type] => 1234
    )

    [3] => Array
    (
        [item] => bbbb
        [type] => 6789
    )

)