2

I have this array:

$categories = array(1,19,4,33,10,7,12);

And this array:

$order = array(33,12,50,19,4,1,100,18,9,2,7);

What I want is for $categories to be sorted in the way that is prefined in $order. So the result I need would be:

$categories_sorted = array(33,12,19,4,1,7,10);

As you may have noticed, 10 is not in $order. This is because the $order array never has all categories in it, only the most important ones. The $categories_sorted array should always contain all values from $categories, even if they are not in $sorted.

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Marcel Emblazoned
  • 593
  • 2
  • 4
  • 16
  • 2
    Would be easiest with [`array_intersect`](http://php.net/array_intersect) and just appending [`array_diff`](http://php.net/array_diff). – mario Jun 16 '15 at 21:24
  • This is a duplicate of a duplicate question http://stackoverflow.com/questions/15294932/php-sorting-an-array-by-predefined-order if I'm correct – wezzy Jun 16 '15 at 21:24
  • And what have you tried so far? – VolenD Jun 16 '15 at 21:25

2 Answers2

0

I hope this achieve your challenge:

$categories = array(1, 19, 4, 33, 10, 7, 12);
$order = array(33, 12, 50, 19, 4, 1, 100, 18, 9, 2, 7);
$categories_sorted = array();

// first: sort what is in $categories based on $order

foreach($order as $key => $value) {
    if(in_array($value, $categories)) $categories_sorted[] = $value;
}

// then add what is in $categories but bot in $order

foreach($categories as $key => $value) {
    if(!in_array($value, $order)) $categories_sorted[] = $value;
}
user2755140
  • 1,917
  • 4
  • 13
  • 16
0

You can use uasort function of php as

$categories = array(1, 19, 4, 33, 10, 7, 12);
$order = array(33, 12, 50, 19, 4, 1, 100, 18, 9, 2, 7);

uasort($categories, function($a, $b)use(&$order) {
    foreach ($order as $key => $value) {
        if ($a == $value) {
            return 0;
            break;
        }
        if ($b == $value) {
            return 1;
            break;
        }
    }
});

print_r($categories);

Fiddle

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54