dqkx69935 2018-07-01 06:29 采纳率: 100%
浏览 71
已采纳

PHP连接2个具有相同键值的数组

I'm wondering how to solved this. I have 3(three) arrays that contained nested values in the "data" key like this:

array:3 [
  0 => array:3 [
    "status" => "Terkirim"
    "warna" => "lightgreen"
    "data" => array:12 [
      0 => 0
      1 => 0
      2 => 0
      3 => 0
      4 => 0
      5 => 0
      6 => 3
      7 => 0
      8 => 0
      9 => 0
      10 => 0
      11 => 0
    ]
  ]
  1 => array:3 [
    "status" => "Selesai"
    "warna" => "lightblue"
    "data" => array:12 [
      0 => 0
      1 => 0
      2 => 0
      3 => 0
      4 => 0
      5 => 0
      6 => 3
      7 => 0
      8 => 0
      9 => 0
      10 => 0
      11 => 0
    ]
  ]
  2 => array:3 [
    "status" => "Selesai"
    "warna" => "lightblue"
    "data" => array:12 [
      0 => 0
      1 => 0
      2 => 0
      3 => 0
      4 => 0
      5 => 0
      6 => 0
      7 => 1
      8 => 0
      9 => 0
      10 => 0
      11 => 0
    ]
  ]
]

My problem is how to join the "data" just if the "status" is the same?, or sum the the value if it already exists on the same index key, this is what I want to achieve:

array:3 [
  0 => array:3 [
    "status" => "Terkirim"
    "warna" => "lightgreen"
    "data" => array:12 [
      0 => 0
      1 => 0
      2 => 0
      3 => 0
      4 => 0
      5 => 0
      6 => 3
      7 => 0
      8 => 0
      9 => 0
      10 => 0
      11 => 0
    ]
  ]
  1 => array:3 [
    "status" => "Selesai"
    "warna" => "lightblue"
    "data" => array:12 [
      0 => 0
      1 => 0
      2 => 0
      3 => 0
      4 => 0
      5 => 0
      6 => 3
      7 => 1 <== the joined value 
      8 => 0
      9 => 0
      10 => 0
      11 => 0
    ]
  ]  
]

Any helps would be appreciated... :)

  • 写回答

2条回答 默认 最新

  • dongyihao1099 2018-07-01 06:44
    关注

    You can do it this way:

        $joinedArray = [];
        for ($initialArray as $array) {
            if (array_key_exists($array['status'], $joinedArray) {
                for ($joinedArray['data'] as $key, $dataElement) {
                     $joinedArray['data'][$key] = $dataElement + $array['data'][$key];
                }
            } else {
                 $joinedArray[$array['status']] = $array;
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退