php - 在多个数组中按键排序
问题描述
我正在尝试创建一个日历(使用 WordPress)。一切正常。但我似乎无法按小时对事件进行排序。
实际上输出是:
Array (
[2020] => Array (
[October] => Array (
[21] => Array (
[18] => Array (
)
[14] => Array (
)
[12] => Array (
)
)
)
[2021] => Array (
[January] => Array (
[12] => Array (
[14] => Array (
)
[13] => Array (
)
[11] => Array (
)
)
)
)
)
我试图得到:
Array (
[2020] => Array (
[October] => Array (
[21] => Array (
[12] => Array (
)
[14] => Array (
)
[18] => Array (
)
)
)
[2021] => Array (
[January] => Array (
[12] => Array (
[11] => Array (
)
[13] => Array (
)
[14] => Array (
)
)
)
)
)
我的数组的结构是这样的:
[$year]
[$month]
[$day]
[$hour]
请问如何[$hour]
在里面点[$day]
餐?
$events_list = array();
if($events) {
foreach($events as $event) {
$date = $date_event = get_field('event_date', $event->ID, false);
$hour = $hour_start = get_field('event_hour_start', $event->ID, false);
$hour_end = get_field('event_hour_end', $event->ID, false);
$date = new DateTime($date);
$hour = new DateTime($hour);
$date_event = $date->format('l j F');
$year = $date->format('Y');
$month = $date->format('F');
$day = $date->format('d');
$hour = $hour->format('G');
$events_list[$year][$month][$day][$hour] = array('datas'=>$event, 'date'=>$date_event, 'hour_start'=>$hour_start, 'hour_end'=>$hour_end);
}
}
ksort($events_list);
解决方案
使用ksort()
,阅读更多关于它的信息。
您的用例的MWE(最小工作示例)将是:
$arr = array(
2021 => array(
"October" => array(
21 => array(
18 => array(),
14 => array(),
12 => array()
)
)
)
);
ksort($arr[2021]["October"][21]);
print_r($arr);
// $arr = array(
// 2021 => array(
// "October" => array(
// 21 => array(
// 12 => array(),
// 14 => array(),
// 18 => array()
// )
// )
// )
// );
此函数还有第二个可选参数名为sort_flags
,它可以占用以下选项之一:
SORT_REGULAR - compare items normally; the details are described in the comparison operators section. This is DEFAULT value
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively
编辑:也适用于表示整数值的字符串键。
推荐阅读
- asp.net-core - Razor 中的 C# 视图输出为字符串文字
- jsf - 如何将内容呈现为纯文本和 URL 编码
- substrate - 可以在基材中使用字符串吗?
- vue.js - 有没有办法替换 Nuxt 中特定模板的基本路径?
- java - Mockito - 多次调用的嵌套方法
- validation - 如何使用 go-playground 验证器在嵌入式结构上运行自定义验证函数
- javascript - 无法从 @typeform/embed 获取 createSlider 以在 React 中工作
- python-3.x - 1064,“您的 SQL 语法有错误 | PyMySQL 更新过程出现错误
- github - 如何使用 IntelliJ/RubyMine/etc 管理多个 GitHub 帐户
- r - 在部署包含库 rsconnect 的 Shiny App 时面临问题