gpt4 book ai didi

javascript - PHP 重新排列数组并按值分组

转载 作者:行者123 更新时间:2023-11-29 10:34:16 25 4
gpt4 key购买 nike

我想按日期重新排列/分组该数组,并合并具有相同日期的值。

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;
}

最佳答案

在这里准备了一个 fiddle :

https://eval.in/881325

完整代码如下:

<?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
)

)

关于javascript - PHP 重新排列数组并按值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com