特定键的多维数组差异比较

5
我有两个产品数组,它们的格式完全相同,如下所示:
$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似乎行不通。

1
“additional ones added to the first” 和 “those not found in the second” 之间的功能区别是什么?发布的解决方案中有没有一个符合您的要求,或者您正在寻找其他内容? - user410344
2个回答

11

我猜您想要类似array_udiff的东西。 这允许您使用回调函数指定如何比较两个数组。 您只需创建一个基于产品ID进行比较的回调即可。

我认为这符合您的需求,因为array_diff系列函数仅将第一个数组与其余数组进行比较,不会返回array1没有但array2(或3、4)有的元素。

<?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)
  }
}

需要特别注意确保比较具有相同结构的数组。将$b['productID']$a['product_id']进行比较将失败。 - Valentin Despa

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,
  ),
)

希望这有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接