doujunchi1238 2014-02-28 09:33
浏览 31
已采纳

将数组列表与数组中的下一个列表进行比较

I would like to compare lists with others in order to merge if their numbers (id_article) are the same. In my example, I would like to obtain this final array list :

*Final *

Array
(
    [0] => Array
        (
            [id_article] => 1
            [quantite] => 5
        )

    [1] => Array
        (
            [id_article] => 3
            [quantite] => 1
        )

}

INITIAL

Array
(
    [0] => Array
        (
            [id_article] => 1
            [quantite] => 2
        )

    [1] => Array
        (
            [id_article] => 1
            [quantite] => 3
        )

    [2] => Array
        (
            [id_article] => 3
            [quantite] => 1
        )

)

I tried with next() and current() but didn't work in this case.

Thanks in advance for help, advice or others examples.

  • 写回答

3条回答 默认 最新

  • dongliyi967823 2014-02-28 09:46
    关注
    $a = array(
        array(
            'id_article' => 1,
            'quantite' => 2,
        ),
        array(
            'id_article' => 1,
            'quantite' => 3,
        ),
        array(
            'id_article' => 3,
            'quantite' => 1,
        ),
    );
    
    $b = array();
    
    foreach ($a as $k => $v) {
        if (array_key_exists($v['id_article'], $b)) {
            $b[$v['id_article']]['quantite'] += $v['quantite'];
        } else {
            $b[$v['id_article']] = $v;
        }
    }
    
    return array_values($b);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!