代码之家  ›  专栏  ›  技术社区  ›  Saad Ahmed

php数组合并[关闭]

  •  -1
  • Saad Ahmed  · 技术社区  · 6 年前

    我有两个这样的阵列:

    Array(
         [0] => (
             [id] => 1,
             [order_id] => 1,
             [image_url] => /resources/filename1
             ),
         [1] => (
             [id] => 2,
             [order_id] => 1,
             [image_url] => /resources/filename2
             )
    )
    

    我想合并 imge_url 在单个数组中,因为 order_id ,一个订单有多个图像。

    我期待这样的数组:

    Array(
        [id] => 1,
        [order_id] => 1,
        [image_url] => (
            [0] => "/resources/filename1",
            [1] => "/resources/filename2"
        )
    )
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   L. Amigo    6 年前

    好吧,很抱歉我之前的回答不对,这一个是对的,我假设有两件事:

    • 您的输入可以超过两行,并且可以有多个订单ID
    • 我正在给id分配第一个具有该订单id的id(如果不是,则只能分配id键)。

    代码如下:

    $arrays = [
        [
            "id" => 1,
            "order_id" => 1,
            "image_url" => "/resources/filename1"
        ],
        [
            "id" => 2,
            "order_id" => 1,
            "image_url" => "/resources/filename2"
        ],
        [
            "id" => 3,
            "order_id" => 1,
            "image_url" => "/resources/filename3"
        ],
            [
            "id" => 4,
            "order_id" => 2,
            "image_url" => "/resources/filename4"
        ],
    ];
    
    foreach($arrays as $array) {
        if(!isset($result[$array['order_id']]['id'])) {
            $result[$array['order_id']]['id']=$array['id'];
        }
        $result[$array['order_id']]['order_id']=$array['order_id'];
        $result[$array['order_id']]['image_url'][]=$array['image_url'];
    }
    print_r($result);
    

    测试 here .

        2
  •  0
  •   Pradeep    6 年前

    希望这对你有帮助:

    工作演示: https://eval.in/1014350

    $array = array(array(
         'id' => 1,
         'order_id' => 1,
         'image_url' => '/resources/filename1'
         ),array(
         'id' => 2,
         'order_id' => 1,
         'image_url' => '/resources/filename2'
         )
    );
    
    foreach ($array as $key => $item) {
      if ($item['id'] == 1)
      {
        $data['id'] = $item['id'];
      }
      $data['order_id'] = $item['order_id'];
      $data['image_url'][$key] = $item['image_url'];
    }
    
    print_r($data);
    

    程序输出

    Array
    (
        [id] => 1
        [order_id] => 1
        [image_url] => Array
            (
                [0] => /resources/filename1
                [1] => /resources/filename2
            )
    
    )