php |数组合并 [英] php | Array merge

查看:59
本文介绍了php |数组合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

Array
(
    [0] => Array
        (
            [qty] => 2
            [id] => 1
            [name] => Name 1
            [sku] => Model 1
            [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
            [price] => 209.00
        )

    [1] => Array
        (
            [qty] => 1
            [id] => 1
            [name] => Name 1
            [sku] => Model 1
            [options] => Color: <em>Black (+10$)</em>. Memory: <em>16GB</em>. 
            [price] => 110.00
        )

    [2] => Array
        (
            [qty] => 1
            [id] => 3
            [name] => Name 2
            [sku] => Model 2
            [options] => 
            [price] => 100.00
        )
)

第一步是找到相同的ID.并且如果存在相同的ID,则转换数组. 是否有可能获得输出数组(如果id相同,则删除一个数组,然后向另一个数组添加数量)?

First step is to find the same id. And if the same id exist convert array. Is it possible to get output array (if id the same remove one and add qty to the another)?

 Array
    (
        [0] => Array
            (
                [qty] => 3 // 2+1
                [id] => 1
                [name] => Name 1
                [sku] => Model 1
                [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
                [price] => 209.00
            )

        [1] => Array
            (
                [qty] => 1
                [id] => 3
                [name] => Name 2
                [sku] => Model 2
                [options] => 
                [price] => 100.00
            )
    )

谢谢!

推荐答案

$result = array();
foreach ($input as $subarray) {
  $id = $subarray['id'];
  if (isset($result[$id])) { // Same ID
    $result[$id]['qty'] += $subarray['qty']; // Add quantities
  } else {
    $result[$id] = $subarray; // New ID, put in results
  }
}
$result = array_values($result); // Convert from associative array to indexed

这篇关于php |数组合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆