问:我知道这是非常基本的。
我试图从下面的对象中获取每个键的 qty 总和,但它没有返回我所期望的。
{
"3": [
{
"id": 1,
"qty": 4,
"customer_id": 3,
"cargo_id": 3,
"customer": {
"id": 3,
"company_name": "Mertz and Sons",
"phone": "(586) 898-5987"
},
}
],
"6": [
{
"id": 3,
"qty": 9,
"customer_id": 6,
"cargo_id": 3,
"customer": {
"id": 6,
"company_name": "Turcotte PLC",
"phone": "+13422302445"
},
},
{
"id": 4,
"qty": 3,
"customer_id": 6,
"customer": {
"id": 6,
"company_name": "Turcotte PLC",
"phone": "+13422302445"
},
}
]
}
这是我目前正在做的事情
$attrs = [];
foreach($record as $item=> $value){
foreach($value as $k){
$attrs['customer'] = $k['customer']['company_name'];
$sum_ordered = 0;
$sum_ordered += $k['qty'];
$attrs['ordered_sum'] = $sum_ordered;
}
$output[] = $attrs;
}
echo json_encode($output);
这就是我得到的结果,我无法弄清楚什么是不对的。我期待 4 和 12 分别为ordered_sum
[
{"customer":"Mertz and Sons","ordered_sum":4},
{"customer":"Turcotte PLC","ordered_sum":3}
]
答:试试这个
$output = [];
foreach($record as $item=> $value){
$attrs = [
'customer' => $value[0]['customer']['company_name'],
'ordered_sum' => 0
];
foreach($value as $k){
$attrs['ordered_sum'] += $k['qty'];
}
$output[] = $attrs;
}
echo json_encode($output);
使用示例array_reduce
$record = [
"3" => [
[
"id" => 1,
"qty" => 4,
"customer_id" => 3,
"cargo_id" => 3,
"customer" => [
"id" => 3,
"company_name" => "Mertz and Sons",
"phone" => "(586) 898-5987"
]
]
],
"6" => [
[
"id" => 3,
"qty" => 9,
"customer_id" => 6,
"cargo_id" => 3,
"customer" => [
"id" => 6,
"company_name" => "Turcotte PLC",
"phone" => "+13422302445"
]
],
[
"id" => 4,
"qty" => 3,
"customer_id" => 6,
"customer" => [
"id" => 6,
"company_name" => "Turcotte PLC",
"phone" => "+13422302445"
]