首页 > 解决方案 > 如何将数量存储在 $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数组中吗?

标签: phplaravel

解决方案


要直接回答您的问题(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. 这样你就没有重复了。但这假设你不想要重复:)


推荐阅读