我想用以下代码获取每种注册类型的数量:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dd($ type_counts),如果会议有2个可用的注册类型(普通和加号),并且用户正在使用2个注册类型为“ general”的参与者和0个注册类型为“ plus”的参与者进行注册显示:
array:2 [▼
"general" => 2
]
然后,我需要向API发出发布请求,以便在请求主体中发送每种注册类型的数量,在这种情况下,只有1个注册类型“常规”,数量的值应为“ 2“。
所以我在上面的代码下面有下面的代码来创建数组:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
$create = $client->request('POST', 'https://...', [
'query' => ['api_key' => '...'], 'json' => $items,
]);
但是输出数组是:
array:1 [▼
"invoice" => array:4 [▼
"client" => array:7 [▶]
"items" => array:2 [▼
0 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
1 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
]
]
]
而不是仅一项:
array:1 [▼
"invoice" => array:4 [▼
"client" => array:7 [▶]
"items" => array:2 [▼
0 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
]
]
]
$ items显示:
array:1 [▼
"invoice" => array:4 [▼
"items" => array:2 [▼
1 => array:5 [▼
"name" => "general"
"unit_price" => 10
"quantity" => 2
]
2 => array:5 [▼
"name" => "plus"
"unit_price" => 0
"quantity" => 2
]
]
]
]
答案 0 :(得分:1)
您需要根据注册类型名称来键入项目的结果:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][$registrationType->registration_type->name] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
如果有一个,最好使用registration_type的ID:
foreach ($registrationTypeDetails->participants as $registrationType) {
$items['invoice']['items'][$registrationType->registration_type->id] = [
'name' => $registrationType->registration_type->name,
'unit_price' => $registrationType->registration_type->price,
'quantity' => $type_counts[$registrationType->registration_type->name],
];
}
说明
当您遍历链接到注册类型的参与者时,多个参与者可能具有相同的注册类型。因此,在您的情况下,您需要根据注册类型对结果进行分组。仅添加到items[]
即可追加到items数组。您想按注册类型对结果进行分组。
修复422验证错误
您的项目是一个有效的数组,但是由于将其转换为json,因此1
和1
将被键作为对象。要强制进行键调整,您可以执行以下操作:
// It is hacky but it re-keys the items array numerically.
$items['invoice']['items'] = array_values($list['invoice']['items']);