我有一个随机发票清单,每个发票都有自己的客户。
我想按客户对发票分组。
我有这个:
$randomInvoices = [
[
"name" => "studio",
"client_id" => 111,
"invoice" => 1233,
"email" => 'studio@studio.com.br'
],
[
"name" => "italiano",
"client_id" => 222,
"invoice" => 6775,
"email" => 'italiano@italia.com'
],
[
"name" => "studio",
"client_id" => 111,
"invoice" => 577,
"email" => 'studio@studio.com.br'
],
[
"name" => "italiano",
"client_id" => 222,
"invoice" => 677543,
"email" => 'italiano@italia.com'
],
];
我想要这个:
$invoicesByClient = [
[
"client_id" => 111,
"name" => "studio",
"invoices" => [1233, 577]
"email" => 'studio@studio.com.br'
],
[
"client_id" => 222,
"name" => "italiano",
"invoices" => [6775, 677543],
"email" => 'italiano@italia.com'
],
];
如何以最简单的方式获得此结果?我尝试了一堆foreach,但是太混乱了。
function getValueByTrigger($array, $triggerKey, $triggerValue, $returnKey) {
$invoices = [];
foreach ($array as $item) {
if($item[$triggerKey] == $triggerValue) {
$invoices[] = $item[$returnKey];
}
}
return $invoices;
foreach ($invoicesByClient as $key => $value) {
$invoicesByClient[$key]['invoices'] = getValueByTrigger($randomInvoices, 'client_id', $value['client_id'], 'invoice');
}
}
答案 0 :(得分:1)
建立循环为:
$invoicesByClient = [];
foreach ($randomInvoices as $value) {
$clientId = $value['client_id'];
if (!isset($invoicesByClient[$clientId])) {
$invoicesByClient[$clientId] = [
"name" => $value['name'],
"client_id" => $clientId,
"email" => $value['email'],
'invoices' => [],
];
}
$invoicesByClient[$clientId]['invoices'][] = $value['invoice'];
}
// use `array_values` to get 0-indexed array
$invoicesByClient = array_values($invoicesByClient);
提琴是here。