[英]PHP sorting 3 dimensional array
I know this would be an easy one but I don't get it. 我知道这很容易,但我不明白。 All answered I found on the net was... too complex to me, maybe. 我在网上发现的所有答案都...也许对我来说太复杂了。
Here is my typical array: 这是我的典型数组:
array(
(int) 0 => array(
'Conversation' => array(
'id' => '1',
'created' => '2012-08-04 00:00:00'
),
'ConversationUser' => array(
(int) 0 => array(
'id' => '1'
),
(int) 1 => array(
'id' => '2'
)
)
),
(int) 1 => array(
'Conversation' => array(
'id' => '2',
'created' => '2012-08-01 00:00:00'
),
'ConversationUser' => array(
(int) 0 => array(
'id' => '1'
),
(int) 1 => array(
'id' => '2'
)
)
));
I want to sort my data with ['Conversation']['created'] date, asc or desc. 我想用['Conversation'] ['created']日期(升序或降序)对数据进行排序。
Any simple answer ? 有简单的答案吗? :P :P
PS I can't use MYSQL sort, I retrieve the data one by one and create that array. PS我不能使用MYSQL排序,我一个接一个地检索数据并创建该数组。
You can use array_multisort to do this: 您可以使用array_multisort来做到这一点:
// $data is your array from the example
// first obtain the rows for sorting
$sortkeys = array();
foreach ($data as $row) {
$sortkeys[] = $row['Conversation']['created'];
}
// sort $data according to $sortkeys
array_multisort($sortkeys, $data);
var_dump($data);
You should have a look to uksort() and usort() functions, which let you customize the way arrays are sorted. 您应该看一下uksort()和usort()函数,它们使您可以自定义数组的排序方式。
Either the solution is simple or complex, remember what Einstein said once: " Things should be always done as simple as possible, but never simpler than they really are ". 无论解决方案是简单还是复杂,请记住爱因斯坦曾经说过的一句话:“ 事情应该总是做得尽可能简单,但永远不要比实际情况简单 ”。
If you have some trouble with these functions, we can give you further clues ;-) 如果您在使用这些功能时遇到问题,我们可以为您提供更多线索;-)
You can use usort()
(or, to maintain index association, uasort()
. Example: (assumes your array is $arr
): 您可以使用usort()
(或者,为了维护索引关联,可以使用uasort()
。例如:(假设您的数组是$arr
):
usort($arr, function($a, $b) {
return
preg_replace('/\D/', '', $b['Conversation']['created'])
>
preg_replace('/\D/', '', $a['Conversation']['created']);
});
That will sort descending. 那将降序排列。 Change >
to <
for ascending. 将>
更改为<
以升序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.