【发布时间】:2018-07-04 23:36:42
【问题描述】:
我想用下面的代码获取每种注册类型的数量:
$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 名注册类型“普通”的参与者和 0 名注册类型“加号”的参与者进行注册显示:
array:2 [▼
"general" => 2
]
然后我需要向 API 发出一个 post 请求,需要在请求正文中发送每个注册类型的数量,在这种情况下,只有 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
]
]
]
]
【问题讨论】:
标签: laravel