PHP数组合并

时间:2018-06-03 09:43:24

标签: php arrays mapping

我有两个像这样的数组:

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,一个order_id有多个图片。

我期待像这样的数组:

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

2 个答案:

答案 0 :(得分:1)

好的,我很抱歉我之前的回答是不对的,这个做了,我假设了几件事:

  • 您的输入可以超过两行,并且可以包含多个订单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

答案 1 :(得分:0)

希望这会对您有所帮助:

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

std::ifstream stream(m_filename, std::ios::in | std::ios::binary);
...
...
// m_header is vector<unsigned cha>
m_header.insert(m_header.begin(),
           std::istream_iterator<unsigned char>(stream),
           std::istream_iterator<unsigned char>()); 

节目输出

$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);