在PHP数组中传播重复值

时间:2016-07-28 13:06:09

标签: php

  
[0] => Array
        (
            [id] => 9
            [order_address_id] => 9
            [created] => 2015-12-17 12:24:20
            [order_status] => dispatched
            [total_discount] => 
            [total_shipping_charge] => 60
            [s_state] => NY
            [b_state] => NY
            [order_id] => 9
            [p_name] => Product 1
            [qty] => 1
            [price] => 475
        )

    [1] => Array
        (
            [id] => 9
            [order_address_id] => 9
            [created] => 2015-12-17 12:24:20
            [order_status] => dispatched
            [total_discount] => 
            [total_shipping_charge] => 60
            [s_state] => MA
            [b_state] => MA
            [order_id] => 9
            [p_name] => Product 2
            [qty] => 1
            [price] => 349
        )

我想找到具有相同ID重复的数组,然后我必须从具有相同id的第二个和后续数组中删除total_shipping_charge。我怎么能在PHP中做到这一点?

1 个答案:

答案 0 :(得分:0)

我会使用array_walk

首先,您要创建一个回调函数来检查是否已经遇到id,如果有,则取消设置total_shipping_charge,如

function shipping_charge_walk(&$entry, $key, &$found_ids)
{
  if (in_array($entry['id'], $found_ids)) {
    unset($entry['total_shipping_charge']);
  } else {
    $found_ids[] = $entry['id'];
  }
}

这会通过引用获取$found_ids,以便它可以将任何遇到的ID附加到它,并通过引用获取$entry,以便它可以取消设置它的成员。

然后,只需在数组上调用array walk。

$found_ids = array();
array_walk($arr, 'shipping_charge_walk', $found_ids);