gpt4 book ai didi

php - 按日期对数组排序

转载 作者:行者123 更新时间:2023-11-29 08:58:48 24 4
gpt4 key购买 nike

我有一个问题。我通过从 mysql 获取数据并将三个查询结果合并到一个数组中来构建一个数组。

我将数据放入数组中,如下所示:

while ($a = mysql_fetch_object($activities)) {
$a->type = 1;
$array1[] = $a;
}
while ($k = mysql_fetch_object($fuups)) {
$k->type = 2;
$array1[] = $k;
}
while ($x = mysql_fetch_object($refuups)) {
$x->type = 3;
$array1[] = $x;
}

return (object)$array1;

这会返回类似这样的内容:

stdClass Object
(
[0] => stdClass Object
(
[added] => 2012-01-17 07:33:53
[type] => 1
)

[1] => stdClass Object
(
[added] => 2012-01-13 06:36:22
[type] => 1
)

[2] => stdClass Object
(
[added_type_2] => 2012-01-09 04:01:12
[type] => 2
)

[3] => stdClass Object
(
[added_type_2] => 2012-02-08 02:08:32
[type] => 2
)

[4] => stdClass Object
(
[added_type_2] => 2012-01-25 00:09:08
[type] => 2
)

[5] => stdClass Object
(
[added_type_3] => 2012-01-23 00:09:08
[type] => 3
)

[6] => stdClass Object
(
[added_type_3] => 2012-01-22 00:09:08
[type] => 3
)

)

我尝试过像 asort、ksort、sort 这样的东西,但没有运气。还可以通过“按添加的描述排序”获取日期,谢谢

最佳答案

您想要做的是对多维数组进行排序,您可以在 Google 上找到很多相关内容。一个优雅的解决方案是这样的:

// Sort the multidimensional array
usort($results, "custom_sort");

// Define the custom sort function
function custom_sort($a,$b) {
return $a['some_sub_var']>$b['some_sub_var'];
}

编辑1:

对于那些在评论中怀疑此代码是否有效的人,请随意尝试一下(我什至添加了一个重复的日期以用于测试目的):

function custom_sort($a,$b) {
return $a['added']>$b['added'];
}

$arrayToSort = array(
array(
"added" => "2012-01-17 07:33:53",
"type" => "1"
),
array(
"added" => "2012-01-13 06:36:22",
"type" => "1"
),
array(
"added" => "2012-01-09 04:01:12",
"type" => "2"
),
array(
"added" => "2012-02-08 02:08:32",
"type" => "2"
),
array(
"added" => "2012-01-25 00:09:08",
"type" => "2"
),
array(
"added" => "2012-01-13 06:36:22",
"type" => "1"
),
array(
"added" => "2012-01-13 06:36:22",
"type" => "1"
),
array(
"added" => "2012-01-23 00:09:08",
"type" => "3"
),
array(
"added" => "2012-01-22 00:09:08",
"type" => "3"
)
);
usort($arrayToSort, "custom_sort");

echo '<pre>';
print_r($arrayToSort);
echo '</pre>';

快速测试的一个好地方是访问 http://writecodeonline.com/php/ .

关于php - 按日期对数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203079/

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