4

I have an array of one structure like below

$array1 = array(
[123] => array('1'=>'1','2'=>'3'),
[345] => array('1'=>'3','2'=>'5'),
[789] => array('1'=>'1','2'=>'5'),
[567] => array('1'=>'6','2'=>'5'),
);

and another array structure as $array2 = array(567,345,789,123);

Now i want to sort this one with php sort function, i mean sort the first array with second one to looks like the desired output something like below

$array1 = array(
[567] => array('1'=>'6','2'=>'5'),
[345] => array('1'=>'3','2'=>'5'),
[789] => array('1'=>'1','2'=>'5'),
[123] => array('1'=>'1','2'=>'3'),
);

I want to get these desired result with any sorting function which is already exists.

Thanks.

3 Answers 3

8

Loop your $array2 and populate a third array as follows:

$array1 = array(
    [123] => array('1'=>'1','2'=>'3'),
    [345] => array('1'=>'3','2'=>'5'),
    [789] => array('1'=>'1','2'=>'5'),
    [567] => array('1'=>'6','2'=>'5'),
);

$array2 = array(567,345,789,123);

$orderedArray = array();
foreach ($array2 as $key) {
    $orderedArray[$key] = $array1[$key];
}

And if you want a function:

function orderArray($arrayToOrder, $keys) {
    $ordered = array();
    foreach ($keys as $key) {
        if (isset($arrayToOrder[$key])) {
             $ordered[$key] = $arrayToOrder[$key];
        }
    }
    return $ordered;
}

$myOrderedArray = orderArray($array1, $array2);
Sign up to request clarification or add additional context in comments.

Comments

6

Or you can use uksort function of php as

uksort($array1, function($a, $b)use($array2) {
    foreach($array2 as $value){
        if($a == $value){
            return 0;
            break;
        }
        if($b == $value){
            return 1;
            break;
        }
    }
});

Fiddle

Comments

0

How about this?

$sortedArray = array_replace(array_flip($array2), $array1); 

2 Comments

May I know why this is downvoted?
Actually, this seems like the simplest approach. +1

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.