2

I have a comma separated string/array:

$input = "facebook,steam,tumblr,email,instagram,twitter,twitch,youtube,pinterest,amazon,disqus";
$input = explode(",", $input);

that I want to be ordered based on another array:

$order = "email,facebook,instagram,twitter,twitch,youtube,steam,pinterest,tumblr,amazon,disqus";
$order = explode(",", $order);

$input will always contain a value that is in $order and I want it to be sorted based on the order that it comes in $order. This is a bit tricky because $input will only contain a subset of values from $order.

For example, an input of twitter,twitch,email,facebook would return email,facebook,twitter,twitch


I have already found This Solution but it does not apply because I am not dealing with keys in my array.

Community
  • 1
  • 1
Bijan
  • 7,737
  • 18
  • 89
  • 149

2 Answers2

9

No need to do any fancy sorting algorithms. You can just do:

array_intersect($order, $input);

This will return an array containing all the values of $order that are present $input. And thankfully this function keeps the original order in $order.


Note: The order of the arguments to array_intersect() is important. Make sure you pass in $order first, since that is your reference array, then pass in $input, just like in the example above. Otherwise it will do the opposite, which is not what you want.

More info: http://php.net/manual/en/function.array-intersect.php

Ian Drake
  • 737
  • 4
  • 7
0

I have not tested, but may be useful to

   function orderByOtherArray($input, $orderedArray){
        $orderedInput = array();
        foreach($orderedArray as $key => $value){
            if(in_array($value, $input)){
                $orderedInput[] = $value;
                if(($key = array_search($value, $input)) !== false) {
                    unset($input[$key]);
                }
            }
        }

        foreach($input as $key => $value){
            $orderedInput[] = $value;
        }

        return $orderedInput;
    }
Deniz Aktürk
  • 362
  • 1
  • 9