RW24 RW24 - 3 months ago 5
PHP Question

Sorting array by other array values

Here's the idea: a user enters his ZIP code.
Based on the inserted ZIP code, I get an array of ZIP codes (distance ordered).

Next I want to order an existing array of ZIP codes based on the distance ordered array.

So basically I have two arrays:


  1. Array which should be ordered

    array(2) {
    [0]=>
    string(4) "2018"
    [1]=>
    string(4) "2500"
    }

  2. Distance ordered array

    array(247) {
    [0]=>
    string(4) "2000"
    [1]=>
    string(4) "2500"
    [2]=>
    string(4) "2050"
    [2]=>
    string(4) "2018"



In this example, my array (number 1) should be ordered like so: [0] => 2500, [1] => 2018

How can I manage this?

Answer

You could use array_intersect() to get only the values of the second array that are also in the first array. And as the function preserves the keys - and so the order -, you only have to renumber them.

$a1=array(2018,2500);
$a2=array(2000,2500,2050,2018);

$a3=array_intersect( $a2 , $a1 );

echo print_r($a3,true);

Result:

Array ( [1] => 2500 [3] => 2018 )