我需要根据getNotifications函数中的值'start_date‘DESC order对通知数组进行排序:
$posts_id_arr = getPoststIds($conn);
foreach ($posts_id_arr as $key => $val) {
$total_arr[$key] = [
'notification' => getNotifications($val['post_id'], $user_id, $conn)
];
}
$response_array = array('data' => $total_arr, 'more things' => $more_array);
echo json_encode($response_array);现在,由于foreach循环,排序是通过post id进行的。
data {
notification:
[
{
post_id: “1",
start_date: "2016-10-10 08:00:00",
},
{
post_id: “1",
start_date: "2016-10-10 12:00:00",
}
],
notification:
[
post_id: “2",
start_date: "2016-10-10 09:00:00",
},
{
post_id: “2",
start_date: "2016-10-10 13:00:00",
}
]
}我需要时间是1: 08:00,2: 09:00,1: 12:00,2: 13:00
发布于 2016-10-10 15:18:34
您可以使用自定义函数通过uasort对数组中的值进行排序。您的日期格式可以使用strcmp进行排序-过去的日期小于将来的日期,因此您可以在比较器中使用它。
function sort_by_date($a, $b) {
return strcmp($a->start_date, $b->start_date);
}
$sorted_posts = uasort($total_arr->notification, 'sort_by_date');
$response_array = array('data' => $sorted_posts, 'more things' => $more_array);发布于 2016-10-10 15:09:10
如果您想使用内部数组进行排序,最好使用usort()方法。
usort -使用用户定义的比较函数按值对数组进行排序
此函数将使用用户提供的比较函数根据数组的值对其进行排序。如果您希望排序的数组需要按一些重要的标准进行排序,则应该使用此函数。
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>对多维数组进行排序时,$a和$b包含对数组第一个索引的引用。
上面的示例将输出:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons替代解决方案:
您可以尝试使用array_multisort(),因为它会根据您需要的顺序对数组进行排序。
$arr = your array;
$sort = array();
foreach($arr as $k=>$v) {
$sort['field'][$k] = $v['field'];
}
array_multisort($sort['field'], SORT_DESC, $arr);
echo "<pre>";
print_r($arr);发布于 2016-10-10 15:10:36
但是,您不需要在foreach中执行排序。
你可以试试下面的代码。相应地更改变量名。
foreach ($points as $key => $val) {
$time[$key] = $val[0];
}
array_multisort($time, SORT_ASC, $points);这是因为array_multisort的工作方式。它对多个数组进行排序,当对$time数组进行排序时,会根据$time中的数组索引对$points数组进行重新排序。不过,array_multisort应该在foreach之后。
希望这能对你有所帮助。
https://stackoverflow.com/questions/39952806
复制相似问题