0

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?

RW24
  • 562
  • 1
  • 8
  • 19
  • 2
    Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – user3942918 Sep 04 '16 at 13:52
  • use rsort($array); – Ish Sep 04 '16 at 13:59
  • @Ish I honestly don't see how this would solve my problem. Can u provide more information? – RW24 Sep 04 '16 at 14:03
  • @PaulCrovella I've read the post. There's so much information that I wouldn't know where to start or what is useful for in my case. Care to answer something more hands-on? – RW24 Sep 04 '16 at 14:06
  • Do I understand correct that the values of array 1 should be ordered by the position they're in in array 2? – Michel Sep 04 '16 at 14:09

1 Answers1

0

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 )

Michel
  • 3,592
  • 4
  • 33
  • 46