[英]How to check same value in a JSON object array and combine them together?
I have this JSON object array.我有这个 JSON 对象数组。 I need to check for same dates and combine the amount.我需要检查相同的日期并合并金额。 I need to do this in PHP.我需要在 PHP 中执行此操作。 (I'm using Laravel) (我正在使用 Laravel)
[
{date : 2020-09-28, amount : 69.95}
{date : 2020-09-28, amount : 69.95}
{date : 2020-10-01, amount : 69.95}
{date : 2020-10-01, amount : 69.95}
{date : 2020-10-01, amount : 319.95}
]
So the output should be like this:所以输出应该是这样的:
[
{date : 2020-09-28, amount : 139.9}
{date : 2020-10-01, amount : 459.85}
]
What is the best way to implement this please?请执行此操作的最佳方法是什么?
This is the solution I have tried:这是我尝试过的解决方案:
$new_values = array();
foreach ($orders as $order) {
$order_total = $order->order_checkout->shoppingcart->getTotalPrice();
$order_date = $order->created_at->format('Y-m-d');
print_r($order_date);
print(" - ");
print_r($order_total);
print "<br/>";
if (array_key_exists($order_date, $new_values)) {
echo $order_date . " found";
} else {
echo "Not found";
}
array_push($new_values, array($order_date => $order_total));
}
print("<br>");
print_r($new_values);
But it doesn't find out the duplicates.但它没有找出重复项。
This works fine这工作正常
$json = '[{
"date": "2020 - 09 - 28",
"amount": 69.95
},
{
"date": "2020 - 09 - 28",
"amount": 69.95
},
{
"date": "2020 - 10 - 01",
"amount": 69.95
},
{
"date": "2020 - 10 - 01",
"amount": 69.95
},
{
"date": "2020 - 10 - 01",
"amount": 319.95
}
]';
$decode = json_decode($json,true);
$res = array();
foreach($decode as $key => $vals){
if(($index = array_search($vals['date'], array_column( $res, 'date'))) !== false) {
$res[$index]['amount'] += $vals['amount'];
$res[$index]['date'] = $vals['date'];
} else {
$res[] = $vals;
}
}
echo json_encode($res,JSON_PRETTY_PRINT);
Output with :输出:
[
{
"date": "2020 - 09 - 28",
"amount": 139.9
},
{
"date": "2020 - 10 - 01",
"amount": 459.85
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.