0
$a= [ '1' => ['key'=>'1','id'=>'4' ],
      '2' => ['key'=>'2','id'=>'1' ],
      '3' => ['key'=>'3','id'=>'5' ]
    ]

$b = [1,5]

so i want to sort array $a so that if $a[*]['id'] is in $b array it should be first.

so in this example the out put should be

$a = ['2' => ['key'=>'2','id'=>'1' ],
      '3' => ['key'=>'3','id'=>'5' ]
      '1' => ['key'=>'1','id'=>'4' ],
    ]

i tried

uasort($a, function($k, $v) use ($b) {
        return in_array($v['id'],$b) ? 1 : -1;
    });

yet failed :(

is there an optimum method for doing such a trick using any of the php sorting functions?

2
  • Have you read the documentation for uasort()? Commented Jan 11, 2014 at 19:43
  • yp, yet didnt know how to dive to reach 'id' value to compare it in the call back function Commented Jan 11, 2014 at 19:55

2 Answers 2

3
uasort($a, function ($x, $y) use ($b) {
    return !in_array($x['id'], $b);
});

You must note that $y is not used and the code will work without referencing it, but I prefer this way for completeness.

X and Y are any two array values. If the sort function returns 1, X is placed last (first Y, last X). If returns -1, X go first (first X, last Y).

In this case, the sort function will return true (equivalent to 1) if $x[id] is not in $b, so the order will be first Y, then X. This sort will move to the last positions all the array values whith id not in $b.

After say that, you can also use this code without $y:

uasort($a, function ($x) use ($b) {
    return !in_array($x['id'], $b);
});
Sign up to request clarification or add additional context in comments.

2 Comments

can you please explain to me what are the variables that uasort pass to the function ? i mean what is $y ?
@Edakos I answered but I feel you have the efficient one so one up from my end :)
0

Here is another implementation

$a= array( '1' => array('key'=>'1','id'=>'4' ), '2' => array('key'=>'2','id'=>'1' ), '3' => array('key'=>'3','id'=>'5' ) );
$b = array(1,5);
asort($a); 
function customuksort($t1, $t2) {
    global $a;

    return $a[$t1] < $a[$t2] ? -1 : 1;
}
uksort($b, 'customuksort');

print_r($a);

The output is

Array ( [1] => Array ( [key] => 1 [id] => 4 ) [2] => Array ( [key] => 2 [id] => 1 ) [3] => Array ( [key] => 3 [id] => 5 ) )

1 Comment

Follow the answer from @Edakos he has better solution.

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.