所以我要实现的是对数据求和并排序到嵌套数组。
所以说我以这种格式接收结果:
{
"resources": "[{\"name\": \"Product 1\", \"brand_id\": \"1\", \"quantity\": 3}]",
"reportable_id": 1,
}
{
"resources": "[{\"name\": \"Product 1\", \"brand_id\": \"1\", \"quantity\": 2}]",
"reportable_id": 1,
}
{
"resources": "[{\"name\": \"Product 2\", \"brand_id\": \"2\", \"quantity\": 2}]",
"reportable_id": 7,
}
{
"resources": "[{\"name\": \"Product 6\", \"brand_id\": \"8\", \"quantity\": 2}]",
"reportable_id": 7,
}
{
"resources": "[{\"name\": \"Product 3\", \"brand_id\": \"3\", \"quantity\": 3}]",
"reportable_id": 4,
}
{
"resources": "[{\"name\": \"Product 3\", \"brand_id\": \"3\", \"quantity\": 3}]",
"reportable_id": 4,
}
结果应该是:
"1": {
{
name: Product 1,
brand_id: 1,
quantity: 5 // see we sum the data of all products with the same brand_id in the reportable ids.
}
}
"7": {
{
name: Product 2,
brand_id: 2,
quantity: 2
},
{
name: Product 6,
brand_id: 8,
quantity: 2
}
}
"4": {
{
name: Product 3,
brand_id: 3,
quantity: 6
}
}
如果我遗漏了reportable_id,那么我基本上可以实现这一点。 正确的做法是什么? 这是到目前为止我得到的,不是,因为将这些项求和并放入正确的数组索引并不完全应该是这样:
function sortObjects($objects)
{
$data = [];
$product_ids = [];
$device_data = [];
foreach($objects as $object) {
$encoded_data = json_decode($object['resources'], true);
$reportable_id = json_decode($object['reportable_id'], true);
foreach($encoded_data as $key => $endoresment) {
$data[$encoded_data[$key]['brand_id']]['name'] = $encoded_data[$key]['name'];
$data[$encoded_data[$key]['brand_id']]['brand_id'] = $encoded_data[$key]['brand_id'];
if (!in_array($encoded_data[$key]['brand_id'], $product_ids)) {
$product_ids[] = $encoded_data[$key]['brand_id'];
$data[$encoded_data[$key]['brand_id']]['quantity'] = $encoded_data[$key]['quantity'];
} else {
$data[$encoded_data[$key]['brand_id']]['quantity'] += $encoded_data[$key]['quantity'];
}
$device_data[$reportable_id] = $data;
}
}
return $device_data;
}
数据将作为php数组返回。