PHP array_unique()-在减少数组之前先做一些逻辑

时间:2020-07-06 02:09:02

标签: php arrays laravel

我有以下数组数据:

array:3 [
  0 => array:5 [
    "menu_id" => 7
    "menu_name" => "Kasagbutan Meals"
    "menu_price" => "100.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
  1 => array:5 [
    "menu_id" => 7
    "menu_name" => "Kasagbutan Meals"
    "menu_price" => "100.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
  2 => array:5 [
    "menu_id" => 6
    "menu_name" => "Coke"
    "menu_price" => "50.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
]

当我用array_unique()运行它时,数据变成这样:

array:2 [
  0 => array:5 [
    "menu_id" => 7
    "menu_name" => "Kasagbutan Meals"
    "menu_price" => "100.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
  2 => array:5 [
    "menu_id" => 6
    "menu_name" => "Coke"
    "menu_price" => "50.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
]

如何在减小数组之前添加qty?我要添加已删除数组项的qty。所以基本上,理想的数组结果应该是这样的:

array:2 [
  0 => array:5 [
    "menu_id" => 7
    "menu_name" => "Kasagbutan Meals"
    "menu_price" => "100.00"
    "qty" => "2" ----> THIS BECOMES 2 BECAUSE THE OTHER ITEM HAS A QTY OF 1.
    "special_instructions" => ""
  ]
  2 => array:5 [
    "menu_id" => 6
    "menu_name" => "Coke"
    "menu_price" => "50.00"
    "qty" => "1"
    "special_instructions" => ""
  ]
]

1 个答案:

答案 0 :(得分:2)

array_unique()只是一个 reduce 操作。您想要的是稍微复杂一点的,因此请使用array_reduce()

$exclude = array_flip(['qty']); // list of properties to exclude when creating a hash

$totals = array_reduce($arr, function($totals, $item) use ($exclude) {
    $id = array_diff_key($item, $exclude);
    ksort($id); // sort by key to always get the same order
    $hash = crc32(json_encode($id));
    if (array_key_exists($hash, $totals)) {
        $totals[$hash]['qty'] += $item['qty'];
    } else {
        $totals[$hash] = $item;
    }
    return $totals;
}, []);

这将建立一个新的数组,该数组以标识值(除qty以外的所有值)的哈希作为键,在找到它已经知道的条目后,将增加{{1} }。

为了提高速度,我使用了JSON编码字符串的CRC32哈希。不过,您几乎可以使用任何哈希/序列化组合。

演示〜https://3v4l.org/YDsfc

特别鸣谢以下帖子: