1

I have an array as follows:

$aq = ['jonathan', 'paul', 'andy', 'rachel'];

Then I have an array as follows:

$bq = ['rachel', 'andy', 'jonathan'];

What I need is to use the second array to filter the first array.

So for this instance, the resulting array should be:

$cq = ['jonathan', 'andy', 'rachel'];

I started working on a solution that uses the highest key as the top value (the head of the array) because what I'm looking for is the top value but that ran into issues and seemed more like a hack.

Is there a simple function in php that can sort my data based on my first array and there respective positions in the array?

1
  • if the order of the first doesnot quite matter, you could just sort both with lexical sorting (e.g. both ascending), so this way the secondone would be in the correct order relating the first array. Commented Aug 2, 2017 at 20:33

2 Answers 2

3

please try this short and clean solution using array_intersect:

$aq = ['jonathan','paul','andy','rachel'];

$bq = ['rachel','andy','jonathan'];

$cq = array_intersect($aq, $bq);

var_export($cq);

the output will be :

array ( 0 => 'jonathan', 2 => 'andy', 3 => 'rachel', )
Sign up to request clarification or add additional context in comments.

Comments

0

You'll have to use a custom sort function. Here we grab the keys of corresponding entries in the "ordering" array and use them to order the working array.

In this example, we give up (return 0) if the key doesn't exist in the ordering array; you may wish to customize that behavior, but this should give you the general idea.

$order = ['jonathan','paul','andy','rachel'];
$arrayToSort =['rachel','andy','jonathan'];

usort($arrayToSort,function($a,$b) use ($order){
  if( ! array_key_exists($a,$order) ) return 0;
  if( ! array_key_exists($b,$order) ) return 0;

  if( array_search($a,$order) > array_search($b,$order) 
      return 1;
  return -1;
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.