[英]Sort multidimensional array secondary key
I'm trying to figure out the correct function in PHP to sort a multidimensional array. 我正在尝试找出PHP中用于对多维数组排序的正确函数。 I considered doing a foreach and then using ksort (this didn't work). 我考虑过进行一次foreach,然后使用ksort(这不起作用)。 I think it might be useful to note that the secondary keys (the numeric ones) are "manually" set (instead of using array_push since the first key in that scenario would be 0 instead of 1). 我认为可能需要注意,辅助键(数字键)是“手动”设置的(而不是使用array_push,因为在这种情况下,第一个键将是0而不是1)。
This is for a single instance so I don't need a class for this or anything super-special, I'm interested in the correct-context function in PHP to make this bit of code more performance oriented (as well as to figure out what I'm doing wrong). 这是针对单个实例的,因此我不需要此类或任何超级特殊的类,我对PHP中的正确上下文函数感兴趣,以使此代码段更加注重性能(并弄清楚我做错了)。
Note I want to keep the PRIMARY keys (e,g, Main and Promotional) their current order. 注意我想保留主键(例如,主键和促销键)的当前顺序。
The unsorted array... 未排序的数组...
Array
(
[Main] => Array
(
[3] => Main2
[2] => Content
[1] => Main1
)
[Promotional] => Array
(
[3] => Promotional1
[2] => Content
[1] => Promotional2
)
)
The desired outcome (sorting by second-level key)... 期望的结果(按二级键排序)...
Array
(
[Main] => Array
(
[1] => Main1
[2] => Content
[3] => Main2
)
[Promotional] => Array
(
[1] => Promotional2
[2] => Content
[3] => Promotional1
)
)
You may try: 您可以尝试:
foreach($array as $key => $data) {
ksort($data);
$array[$key] = $data;
}
You could also try this: 您也可以尝试以下方法:
foreach($array as $key => &$data) {
ksort($data);
}
the ampersand before the $data variable indicates that the $data variable is a pointer, and any changes to that variable will cascade back to the original configuration. $ data变量前的与号表示$ data变量是一个指针,对该变量的任何更改都将级联回到原始配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.