示例代码数组:https://eval.in/639002
有(user_id = 1)的访客购买了多张票(ticket_id = 1& 2)On事件(event_id = 11)。
我期待结果格式:
[ticket] => Array
(
[1] => Ticket Name, ***
[2] => Ticket Name
)
下面的代码示例:
$data_db = array(
array(
'id' => 1,
'user_id' => 1,
'event_id' => 11,
'ticket_id' => 1,
'user_name' => 'guest 1'
),
array(
'id' => 2,
'user_id' => 2,
'event_id' => 11,
'ticket_id' => 1,
'user_name' => 'guest 2'
),
array(
'id' => 3,
'user_id' => 3,
'event_id' => 22,
'ticket_id' => 1,
'user_name' => 'guest 3'
),
array(
'id' => 4,
'user_id' => 1,
'event_id' => 11,
'ticket_id' => 2,
'user_name' => 'guest 1'
)
);
$output = [];
foreach ( $data_db as $key => $row ) {
$output[ $row['event_id'] ]['event'] = 'Event Name';
$output[ $row['event_id'] ]['attendee'][ $row['user_id'] ] = $row;
$output[ $row['event_id'] ]['attendee'][ $row['user_id'] ]['ticket'][ $row['ticket_id'] ] = 'Ticket Name';
}
print_r($output);
当前结果
Array
(
[11] => Array
(
[event] => Event Name
[attendee] => Array
(
[1] => Array
(
[id] => 4
[user_id] => 1
[event_id] => 11
[ticket_id] => 2
[user_name] => guest 1
[ticket] => Array
(
[2] => Ticket Name
)
)
[2] => Array
(
[id] => 2
[user_id] => 2
[event_id] => 11
[ticket_id] => 1
[user_name] => guest 2
[ticket] => Array
(
[1] => Ticket Name ***
)
)
)
)
[22] => Array
(
[event] => Event Name
[attendee] => Array
(
[3] => Array
(
[id] => 3
[user_id] => 3
[event_id] => 22
[ticket_id] => 1
[user_name] => guest 3
[ticket] => Array
(
[1] => Ticket Name
)
)
)
)
)
答案 0 :(得分:0)
首先,你可以从一个票证阵列中找出哪个票证属于哪个用户:
$output = [];
foreach($data_db as $key=>$row) {
// Define new $tickets Array E.g ['guest_name']=>['ticket_id']
$tickets[$row['user_name']][] = $row['ticket_id'];
$output [] = [
'id'=>$row['id'],
'user_id'=>$row['user_id'],
'event_id'=>$row['event_id'],
'user_name'=>$row['user_name'],
'tickets'=>[]
];
}
$ ticket的输出如下:
Array
(
[guest 1] => Array
(
[0] => 1
[1] => 2
)
[guest 2] => Array
(
[0] => 1
)
[guest 3] => Array
(
[0] => 1
)
)
然后你可以把它们组合起来,就像这样:
foreach($output as $k=>$v){
foreach($tickets as $guest=>$ticket){
if($v['user_name'] == $guest){
$output[$k]['tickets'] = $ticket;
}
}
}
您的输出是:
Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[event_id] => 11
[user_name] => guest 1
[tickets] => Array
(
[0] => 1
[1] => 2
)
)
[1] => Array
(
[id] => 2
[user_id] => 2
[event_id] => 11
[user_name] => guest 2
[tickets] => Array
(
[0] => 1
)
........