0

我有 2 个数组,想将它们合并在一起,并且在第二个数组中找不到该项目,插入一个具有空值的键。基本上在array1中添加来自array2的项目,匹配2个array1子键;Array2 不必与数组 1 的长度相同,它的长度总是更小。

数组1

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

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

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

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

和数组2:

[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] = ''

我在这里尝试了几个建议,它们都归结为一维数组或匹配索引。有什么建议吗?

4

4 回答 4

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
于 2012-06-11T11:41:58.033 回答
0

你有没有尝试过这样的事情?

foreach ($array1 as $key=>$value){
   if (isset($array2[$key]['feature'])){
      $array1[$key]['feature'] = $array2[$key]['feature'];
   } else {
      $array1[$key]['feature'] = '';
   }
}
于 2012-06-11T11:28:29.873 回答
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);
于 2012-06-11T11:34:55.437 回答
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
    )

)
于 2012-06-11T11:56:40.427 回答