Jump to content

Sort 2D array (by value of second element)


springo

Recommended Posts

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

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.

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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.