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条)

报告相同问题?