0

Assuming that I have following situation:

I have an array like this:

$array = array(1 => "text1",2 => "text2", 3 => "Text3" , 4 => "Text4");

After some functions I receive a string which contains these values:

$string = "2,1,4,3"; // this values are dynamic 

What I want to achieve is to sort that array ($array) in the string's order; so the result should be:

<--- some function --- > 
$result = array(2 => "text2",1=> "text1",4=>"Text4",3=>"Text3"));
2
  • Please don't tell me you are getting these dynamic values from a database. Commented Dec 2, 2011 at 23:40
  • no , this are randomly received by custom function .. thanks Commented Dec 3, 2011 at 11:37

3 Answers 3

1
$keyArr = explode(',', $string);
$sortedArr = array();

foreach ($keyArr as $key)
{
    $sortedArr[$key] = $array[$key];
}
Sign up to request clarification or add additional context in comments.

Comments

1

PHP's array_multisort() function - http://php.net/manual/en/function.array-multisort.php

Untested, but probably something like:

array_multisort(explode(",", $string), $array);

Keys may get lost though.

Comments

0
  1. Break up the string into indexes with explode
  2. Make an empty array $result
  3. Iterate over the exploded array of keys, doing $result[$key] = $input[$key]

See it in action.

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.