按键值排序数组

I have the following array

Array ( [0] => Array ( [lastUpload] => [lastPost] => Sun Nov 23 2014 16:54:13 [username] => blt152561 [email] => user1@mail.com [joined] => Sun Nov 23 2014 16:49:09 [prodCount] => 2 [mediaCount] => 0 [userId] => 77292aaf-e540-465c-9319-8dd74c8d7f12 ) [1] => Array ( [lastUpload] => [lastPost] => [username] => mvbg40 [email] => user2@mail.com [joined] => Sun Nov 23 2014 9:31:43 [prodCount] => 0 [mediaCount] => 0 [userId] => a2998c68-1c9a-49b9-8c78-ced3cffaa109 ) [2] => Array ( [lastUpload] => Sun Nov 23 2014 7:54:03 [lastPost] => Sun Nov 23 2014 7:53:53 [username] => flexingladies [email] => user5@mail.com [joined] => Sun Nov 23 2014 7:47:44 [prodCount] => 1 [mediaCount] => 1 [userId] => 3b4b6aad-de95-428c-95ed-cb4fe963f322 ) [3] => Array ( [lastUpload] => [lastPost] => Sat Nov 22 2014 8:05:30 [username] => dewey [email] => user3@mail.com [joined] => Sat Nov 22 2014 8:02:01 [prodCount] => 1 [mediaCount] => 0 [userId] => 08220286-6a24-49ff-929b-ccb4e0e10c3e ) [4] => Array ( [lastUpload] => [lastPost] => Thu Nov 20 2014 18:43:56 [username] => mhirsen99 [email] => user4@mail.com [joined] => Thu Nov 20 2014 18:43:09 [prodCount] => 1 [mediaCount] => 0 [userId] => ddea4f04-b035-4e8d-a777-cb4a2813b705 ) )

Which I would like to sort by the value in lastPost.

I have no idea how to go about doing this. Can someone point me in the right direction? I tried ksort but its simply returning 1 and not the sorted array.

dqf42223
dqf42223 或者php.net结束
接近 5 年之前 回复
drhdjp97757
drhdjp97757 只需搜索stackoverflow
接近 5 年之前 回复

3个回答

You have to use foreach to make this work :

foreach ($array as $key => $value)
  $ordered[$value['lastPost']] = $value;

ksort($ordered, SORT_ASC);
dongye6377
dongye6377 您可以使用!empty(),isset()或array_key_exists()来禁止它们包含在已排序的数组中php.net/manual/en/function.array-key-exists.php
接近 5 年之前 回复
doubi4435
doubi4435 这有点起作用,但是由于某种原因,没有['lastPost']键的那些分散在结果中,并且应该都在底部/顶部,这取决于排序否?
接近 5 年之前 回复

try using this

asort($array);

to sort the arrays in ascending order, according to the value

or

arsort($array) ;

to sort the arrays in descending order, according to the value

展开翻译

译文



尝试使用此</ p>

  asort($ array); 
</ code > </ pre>

根据值</ p>

或</ p>

 按升序对数组进行排序 arsort($ array); 
</ code> </ pre>

根据值</ p>
</ div>按降序对数组进行排序

You can use usort for custom sorting by key

usort($array, function($a, $b) { return $a['lastPost'] - $b['lastPost']; });

展开翻译

译文



您可以使用usort按键进行自定义排序</ p>

usort($ array, 函数($ a,$ b){return $ a ['lastPost'] - $ b ['lastPost'];}); </ code> </ p>
</ div>

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!