多维数组中特定键的数组diff

时间:2010-08-17 18:58:41

标签: php arrays comparison multidimensional-array

我有两个产品阵列,两者的格式完全相同,如下所示:

$products = array(
    [0] => array(
        ['product_id'] => 33
        ['variation_id'] => 0
        ['product_price'] => 500.00
    ),
    [1] => array(
        ['product_id'] => 48
        ['variation_id'] => 0
        ['product_price'] => 600.00
    ),
)

我希望能够根据产品ID返回仅在第二个数组中找不到的产品的列表。

我只关心那些在第二个数组中找不到的,而不是第一个中添加的那些,所以array_diff似乎不会这样做。

2 个答案:

答案 0 :(得分:10)

我怀疑你想要像array_udiff这样的东西。这允许您使用回调函数指定如何比较两个数组。您只需创建一个基于产品ID进行比较的回调。

我认为这满足了你想要的,因为array_diff函数系列只将第一个数组与其余数组进行比较,它不会返回array2(或3或4)具有array1不具有的元素。

<?php
$products = array(
    0 => array(
        'product_id' => 33,
        'variation_id' => 0,
        'product_price' => 500.00
    ),
    1 => array(
        'product_id' => 48,
        'variation_id' => 0,
        'product_price' => 600.00
    )
);

$products2 = array(
    1 => array(
        'product_id' => 48,
        'variation_id' => 0,
        'product_price' => 600.00
    ),
    2 => array(
        'product_id' => 49,
        'variation_id' => 0,
        'product_price' => 600.00
    )
);

function compare_ids($a, $b)
{
  return $b['product_id'] - $a['product_id'];
}

var_dump(array_udiff($products, $products2, "compare_ids"));
?>

输出:

array(1) {
  [0]=>
  array(3) {
    ["product_id"]=>
    int(33)
    ["variation_id"]=>
    int(0)
    ["product_price"]=>
    float(500)
  }
}

答案 1 :(得分:4)

一个简单的foreach循环就足够了:

<?php
$products = array(
    0 => array(
        'product_id' => 33,
        'variation_id' => 0,
        'product_price' => 500.00
    ),
    1 => array(
        'product_id' => 48,
        'variation_id' => 0,
        'product_price' => 600.00
    )
);

$products2 = array(
    1 => array(
        'product_id' => 48,
        'variation_id' => 0,
        'product_price' => 600.00
    ),
    2 => array(
        'product_id' => 49,
        'variation_id' => 0,
        'product_price' => 600.00
    )
);

$diff = array();

// Loop through all elements of the first array
foreach($products2 as $value)
{
  // Loop through all elements of the second loop
  // If any matches to the current element are found,
  // they skip that element
  foreach($products as $value2)
  {
    if($value['product_id'] == $value2['product_id'])
    continue 2;
  }
  // If no matches were found, append it to $diff
  $diff[] = $value;
}

$ diff数组只会保存以下值:

array (
  0 => 
  array (
    'product_id' => 49,
    'variation_id' => 0,
    'product_price' => 600,
  ),
)

希望这有帮助!