Jump to content

How do I sort an array by the order of another array?


RJP1

Recommended Posts

Hi guys,

 

I'm trying to sort an array. The array has information about listings. ID, name, info etc.

 

An unrelated set of data also contains the listing ID's and I have made a function to sort this array and show an new order for the ID's. I now need to sort the original array by this new ID order...

 

This snippet shows that the original listings array can be sorted by link_id:

sort($this->links, $this->link->link_id); //This works. It sorts links by link ID!

 

In a foeach loop I have created this:

$sleeps_array[] = array("ID" => $link->link_id, "Sleeps" => $sleeps); // Makes an array of arrays of a custom field with listing ID.

 

It makes this:

array ( 0 => array ( 'ID' => '9', 'Sleeps' => '2', ), 1 => array ( 'ID' => '3', 'Sleeps' => '4', ), 2 => array ( 'ID' => '6', 'Sleeps' => '6', ), )

 

I can then sort this array of arrays with this function:

 

function compare_sleeps($a, $b){
return strnatcmp($a['Sleeps'], $b['Sleeps']);
} # sort alphabetically by name
usort($sleeps_array, 'compare_sleeps');

 

It then gives me a sorted array according to "Sleeps" (as in, the number of people a property can cater for). It has the correct order of ID to then output but how do I organise the original array by ID with this new array?

 

Sounds complicated, I hope you got that!

 

Cheers, RJP1

Not tested, but it should be easier if you created the sleeps array like this:

 

$sleeps_array[$link->link_id] = $sleeps; 

 

Then sort each one, one by value, one by key:

 

sort($this->links);
ksort($sleeps_array);

 

Then do a multisort using the sleeps array as the array to sort with:

 

array_multisort($sleeps_array, $this->links);

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.