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

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.