php - 如何将数量存储在 $regTypes 数组中?
问题描述
我想要一个数组,其中包含与注册相关的每个注册类型的信息。例如,如果对于 id 为“1”的注册,用户选择了两种“General”类型的注册类型和一种“Plus”类型的注册类型,则 $regTypes 数组应包含以下内容和 2 项:
'registrationTypes' => [
[
'name' => 'general',
'price' => '5',
'quantity' => '2'
],
[
'name' => 'plus',
'price' => '10',
'quantity' => '1'
]
]
registration_types 表有名称和价格。所以我有这个查询来获取有关会议注册的一些信息。
$registration = Registration
::with('conference', 'Conference.registrationTypes')->where('id', 1)->first();
然后我有这段代码来创建包含必要信息的数组:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$regTypes [
'regType' => [
'name' => $registration->conference->registrationTypes[$key]['name'],
'price' => $registration->conference->registrationTypes[$key]['price']
]
];
}
我的疑问是如何将数量也存储在 $regTypes 数组中。因为数量没有存储在数据库中。
也许要获得数量需要做antoher查询。使用以下代码:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
//dd($registrationTypeDetails);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dump($type_counts);
显示$type_counts
与注册相关的每种注册类型的数量:
array:2 [▼
"general" => 2
"plus" => 1
]
您知道如何使用此$type_counts
内容将数量正确存储在$regTypes
数组中吗?
解决方案
要直接回答您的问题(IE 不更改控制器代码,只需“使用此$type_counts
内容将数量正确存储在$regTypes
数组中”),我希望这对您有用:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$typeName = $registration->conference->registrationTypes[$key]['name'];
$regTypes [
'regType' => [
'name' => $typeName,
'price' => $registration->conference->registrationTypes[$key]['price'],
'quantity' => $type_counts[$typeName]
]
];
}
$type_counts
基本上只是根据注册类型的名称从数组中提取计数,该名称是您在foreach ($registrationTypeDetails->participants as $p)
循环中添加的键。
根据您所追求的,仅循环注册类型可能更容易,而不是通过$registration->conference->registrationTypes
. 这样你就没有重复了。但这假设你不想要重复:)
推荐阅读
- sql-server - 将表上的 NULL 转换为空白
- swift - 如何向 Google API 发出授权获取请求?
- ios - IDEDebugSessionErrorDomain:LLDB 未提供错误字符串
- kubernetes - 在我的 Helm 模板中,为什么 pluck 评估为 float64?
- java - visualvm 是否能够检测活锁?
- flutter - 如何处理以日期时间为键的json字符串/地图?
- spring - 在 spring-boot 2.4 和 spring cloud 2020 中使用 openfeign 实现断路器
- scala - 如何使用包含选择字符串 DataFrame?
- python - 什么时候可以在“__init__()”之外声明实例属性?
- debugging - Visual Studio Code - 使用 Chrome 进行调试 - 断点在开始时运行,而不是在遇到时