[英]PHP re-arrange array and group by value
我想按日期重新排列/將此數組分組,並合並具有相同日期的值。
Array
(
[0] => stdClass Object
(
[pc] => 100
[date] => 2017-10-03
)
[1] => stdClass Object
(
[pi] => 1
[date] => 2017-10-16
)
[2] => stdClass Object
(
[so] => 10
[date] => 2017-10-12
)
[3] => stdClass Object
(
[so] => 2
[date] => 2017-10-16
)
)
輸出將是:
Array
(
[0] => stdClass Object
(
[date] => 2017-10-03
[pc] => 100
)
[1] => stdClass Object
(
[date] => 2017-10-12
[so] => 10
)
[2] => stdClass Object
(
[date] => 2017-10-16
[pi] => 1
[so] => 2
)
)
我試過了:
$new = array();
foreach ($query as $opt) {
$date = date('Y-m-d',strtotime($opt->date));
$new[$date] = $opt;
}
在這里准備了一個小提琴:
這是完整的代碼:
<?php
// initial array
$array = [
(object)[
"pc" => 100,
"date" => "2017-10-03"
],
(object)[
"pi" => 1,
"date" => "2017-10-16"
],
(object)[
"so" => 10,
"date" => "2017-10-12"
],
(object)[
"so" => 2,
"date" => "2017-10-16"
]
];
// formatted array container
$newArray = [];
// loop each variable and collect the same dated values
// together using date as the key
foreach($array as $val){
if(!isset($newArray[$val->date])) $newArray[$val->date] = [];
foreach(get_object_vars($val) as $key => $prop){
if($key != "date"){
$newArray[$val->date][$key] = $prop;
}
}
}
// restructure the array to convert the keys into sub keys
$index = 0;
foreach($newArray as $key => $value){
$newArray[$index]["date"] = $key;
foreach($value as $key2 => $value2){
$newArray[$index][$key2] = $value2;
}
unset($newArray[$key]);
$newArray[$index] = (object)$newArray[$index];
$index++;
}
// sort the last array
usort($newArray, function($a, $b){
if(date_parse_from_format("YYYY-MM-DD", $a->date) > date_parse_from_format("YYYY-MM-DD", $b->date)){
return 1;
}else if(date_parse_from_format("YYYY-MM-DD", $a->date) < date_parse_from_format("YYYY-MM-DD", $b->date)){
return -1;
}else{
return 0;
}
});
// output the result
print_r($newArray);
?>
輸出:
Array
(
[0] => stdClass Object
(
[date] => 2017-10-03
[pc] => 100
)
[1] => stdClass Object
(
[date] => 2017-10-12
[so] => 10
)
[2] => stdClass Object
(
[date] => 2017-10-16
[pi] => 1
[so] => 2
)
)
您可以使用usort函數
$array = usort($array, function($a, $b){
return date('Y-m-d', strtotime($a['date'])) > date('Y-m-d',
strtotime($b['date']))
})
嘗試這個:
$auxResult = array();
foreach ($query as $item) {
if (!isset($auxResult[$item->date])) {
$auxResult[$item->date] = array();
}
$auxResult[$item->date] = (object) array_merge((array) $auxResult[$item->date], (array) $item);
}
$result = array_values($auxResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.