【问题标题】:PHP array_unique() - do some logic first before reducing the array [duplicate]PHP array_unique() - 在减少数组之前先做一些逻辑[重复]
【发布时间】:2020-10-26 02:53:39
【问题描述】:

我有这个数组数据:

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" => ""
  ]
]

【问题讨论】:

  • 您是否从关系/nosql 数据库中获取该数据?
  • 是什么让一个条目等于另一个条目?只是menu_id 属性还是它也考虑了其他属性?
  • @Phil - 如果它们在以下键中具有相同的值: - menu_id - menu_name - menu_price - special_instructions 所以基本上除了qty
  • 所以你是说条目可以有相同的menu_id 但不同的menu_namemenu_price 等?如果它不能识别记录,那么有一个名为 "id" 的字段有什么意义?
  • @Phil - 实际上,不。理想情况下,如果他们有相同的menu_id,它也会有相同的menu_namemenu_price 等。我包括menu_id,因为我是在前端返回这些数据,我的 JS 代码也在做一些逻辑。

标签: php arrays laravel


【解决方案1】:

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;
}, []);

这会构建一个新数组,该数组由 identifying 值(除了qty 之外的所有值)的哈希值(除qty 之外的所有值)作为键,在找到它已经知道的条目时,增加qty

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

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

对以下帖子的特别点头:

【讨论】:

  • 感谢,但我尝试在 special_instructions 中添加不同的值,但它将它与其他没有 special_instructions 值的值结合在一起。这是在它运行您的代码之前:pastebin.com/hG8C35Q0 注意到另一个在special_instructions 中有一个值,这是在您的代码之后:pastebin.com/sCu76Que 理想的输出应该是这样的:pastebin.com/Gk5ttWEr
猜你喜欢
  • 2022-10-05
  • 2021-10-23
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多