根据内部数组的值和重复值重新排列多维数组

时间:2018-10-12 09:10:45

标签: php arrays multidimensional-array duplicates

我有一个像这样的数组:

Array(
[0] => Array
    (
        [route_id] => 1539871200
        [booking_id] => 171
        [route] => Boattrip Destination 2
        [date] => 18 October 2018 
        [time] => 14:00 - 16:00
    )

[1] => Array
    (
        [route_id] => 1539856800
        [booking_id] => 170
        [route] => Boattrip Destination 2
        [date] => 18 October 2018 
        [time] => 10:00 - 12:00
    )

[2] => Array
    (
        [route_id] => 1539856800
        [booking_id] => 162
        [route] => Boattrip Destination 2
        [date] => 18 October 2018 
        [time] => 10:00 - 12:00
    )
)

Route_id始终共享相同的datetimeroute值。唯一不同的是预订ID。

现在我想要按route_id对数组进行排序,然后创建具有以下结构的新数组

Array (

[1539871200] => Array
    (
    [route] => Boattrip Destination 2
    [date] => 18 October 2018 
    [time] => 14:00 - 16:00
    [booking_ids] => Array
        (                  
           [0] => 171               
        )
    )

[1539856800] => Array
    (
    [route] => Boattrip Destination 2
    [date] => 18 October 2018 
    [time] => 10:00 - 12:00
    [booking_ids] => Array
        (
            [0] => 170
            [1] => 162    
        )
    )
)

这是我的尝试

$output = array();
foreach($bookings as $item) {
    if(!isset($output[$item['route_id']])) {
        $output[$item['route_id']] = array();
    }
    $catName = $item['route_id'];
    unset($item['route_id']);
    $output[$catName][] = $item;
}

但这仅将route_id分组。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

getContent()

答案 1 :(得分:0)

我已按照最佳做法提供了您确切的期望输出。不会生成不必要的变量。没有unset()个呼叫。代码段中唯一的功能是ksort(),我什至不确定您是否想要它。

代码:(Demo

foreach ($array as $set) {
    if (isset($result[$set["route_id"]])) {
        $result[$set["route_id"]]["booking_ids"][] = $set["booking_id"];  // push new element
    } else {
        $result[$set["route_id"]] = [
            "route" => $set["route_id"],            // new key name, transfer value
            "date" => $set["date"],                 // transfer key and value
            "time" => $set["time"],                 // transfer key and value
            "booking_ids" => [$set["booking_id"]]   // new key name, write value as first element
        ];
    }
}
ksort($result);  // ... you did say you wanted to sort them by route_id
var_export($result);

输出:

array (
  1539856800 => 
  array (
    'route' => 1539856800,
    'date' => '18 October 2018',
    'time' => '10:00 - 12:00',
    'booking_ids' => 
    array (
      0 => 170,
      1 => 162,
    ),
  ),
  1539871200 => 
  array (
    'route' => 1539871200,
    'date' => '18 October 2018',
    'time' => '14:00 - 16:00',
    'booking_ids' => 
    array (
      0 => 171,
    ),
  ),
)