9

I have an array of products and i want to sort them with another array.

$products = array(
  0 => 'Pro 1',
  1 => 'Pro 2',
  2 => 'Pro 3'
);

$sort = array(1,2,0);

array_multisort($products, $sort);

Array should now be ...

$products = array(
  0 => 'Pro 2',
  1 => 'Pro 3',
  2 => 'Pro 1'
);

I don't seem to be using array_multisort correctly. Ive tried different ways for 2 hours now...

3
  • 1
    does element indexes always match the numbers in $sort array? Commented Jan 19, 2012 at 23:55
  • I think with array(1,2,0) it should be 3,1,2, when you want 2,3,1 you should use array(2,0,1) Commented Jan 20, 2012 at 0:01
  • 2
    Vyktor is correct if you want to use array_multisort($sort, $products), the array needs to be [2,0,1]. Think of it in terms of "I want the first element of $products to be @ index 2, the second element to be at index 0, and the third element to be at index 1." With your current array, you just need to use some form of iteration (i.e., array_map) as the answers given illustrate. Commented Jan 20, 2012 at 0:55

3 Answers 3

9

It seems like this is more appropriate than a sort:

$products = array_map(function($i) use ($products) {
   return $products[$i];
}, $sort);
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, is there another way to write this one? Dreamweaver thinks its invalid php
@tuurbo, it's valid for PHP 5.3+. Whether or not Dreamweaver thinks it is valid is irrelevant... Either of the other answers will work on older versions of PHP.
2

array_multisort sorts the 2nd array and applies the sorting order to the 1st one. To do your job the sorting array has to be $sort = array(2,0,1); (implies: bring 2nd element to 0, 3rd element to 1 and 1st element to 2).

You simply can use

foreach ($sort as $key) {
    $sorted_products[] = $products[$key];
}

1 Comment

+1, because if I had read this earlier, I wouldn't have needed to leave a comment on the question itself.
1

array_multisort() will not do what you are trying to achieve with that particular code.

Here is a function that will:

function sort_by_other_array ($input, $order) {
  $result = array();
  foreach ($order as $item) {
    $result[] = $input[$item];
  }
  return $result;
}

This does not error checking but will do what you want. You may need to add checks to ensure that the keys specified in $order are present in $input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.