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

Ian*_*ber 4 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
    ),
)
Run Code Online (Sandbox Code Playgroud)

我希望能够根据产品ID返回仅在第二个阵列中找不到的那些产品的列表.

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

Bra*_*ley 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"));
?>
Run Code Online (Sandbox Code Playgroud)

输出:

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


Frx*_*rem 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;
}
Run Code Online (Sandbox Code Playgroud)

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

array (
  0 => 
  array (
    'product_id' => 49,
    'variation_id' => 0,
    'product_price' => 600,
  ),
)
Run Code Online (Sandbox Code Playgroud)

希望这有帮助!