springo Posted March 23, 2007 Share Posted March 23, 2007 Hi, I was looking forward to sorting an array by the value of the second element. e.g.: Sort by number of hits <?php $webs = array ( array("url" => "example.com", "name" => "example 1", "hits" => "5"), array("url" => "example.org", "name" => "example 2", "hits" => "20"), array("url" => "example.net", "name" => "example 3", "hits" => "10") ); ?> Thank you very much! Link to comment https://forums.phpfreaks.com/topic/44022-sort-2d-array-by-value-of-second-element/ Share on other sites More sharing options...
per1os Posted March 23, 2007 Share Posted March 23, 2007 http://us3.php.net/manual/en/function.array-multisort.php Link to comment https://forums.phpfreaks.com/topic/44022-sort-2d-array-by-value-of-second-element/#findComment-213749 Share on other sites More sharing options...
springo Posted March 23, 2007 Author Share Posted March 23, 2007 Thanks for the ressource! After some time working, I got to this, but it won't work: <?php foreach ($webs as $index => $row) { $name[$index] = $row["name"]; $url[$index] = $row["url"]; $hits[$index] = $row["hits"]; } array_multisort($hits, SORT_DESC, $name, $url, $links); ?> What's wrong with it? Thank you again. Link to comment https://forums.phpfreaks.com/topic/44022-sort-2d-array-by-value-of-second-element/#findComment-213809 Share on other sites More sharing options...
Barand Posted March 23, 2007 Share Posted March 23, 2007 I prefer custom sort functions with usort() for multi_D arrays. (I sort by "hits" in the example as the names are already sorted) <?php $webs = array ( array("url" => "example.com", "name" => "example 1", "hits" => "5"), array("url" => "example.org", "name" => "example 2", "hits" => "20"), array("url" => "example.net", "name" => "example 3", "hits" => "10") ); function my_sort ($a, $b) { // change "hits" to "name" to sort by name element if ($a['hits'] == $b['hits']) return 0; // if element a should sort above element b, return -1 // otherwise return 1 return ($a['hits'] < $b['hits']) ? -1 : 1; } usort ($webs, 'my_sort'); echo '<pre>', print_r($webs, true), '</pre>'; ?> Link to comment https://forums.phpfreaks.com/topic/44022-sort-2d-array-by-value-of-second-element/#findComment-213812 Share on other sites More sharing options...
springo Posted March 23, 2007 Author Share Posted March 23, 2007 Barand I got it with that one, just had a problem with the output order until I discover I had to intval() the "hits" which were strings. Thanks! Link to comment https://forums.phpfreaks.com/topic/44022-sort-2d-array-by-value-of-second-element/#findComment-213932 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.