2

I want to sort an array referencing the position of a property in another array for example.

$referenceArray = ['red', 'green', 'blue'];
$testArray = [obj1, obj2, obj3, obj4];

foreach($testArray as $object) {
    if($object->colour === "red") {
        // push to TOP of array
    } elseif($object-color == "green") {
        // push to MIDDLE of array
    } elseif($object->color === "blue") {
       // push to BOTTOM o array 
    }
}

Is this possible using a inbuilt php sort method? or can it only be done such as I have pseudo coded above.

Kind regards

mary_berry
  • 1,384
  • 2
  • 13
  • 23
  • 1
    See http://php.net/array-multisort – Dormilich Dec 10 '18 at 10:31
  • 1
    Basically answered in https://stackoverflow.com/a/17364128/476, under *Sorting into a manual, static order*. Do you have any specific problems applying that here? – deceze Dec 10 '18 at 10:36

1 Answers1

1

Since you have objects within the array then you can't really use any built-in method other than usort unless you are willing to cast the objects to arrays:

$referenceArray = ['red', 'green', 'blue'];
$testArray = [obj1, obj2, obj3, obj4];

usort($testArray, function ($x, $y) use ($referenceArray) {
     $xIndex = array_search($x->color, $referenceArray); //Is it color or colour? 
     $yIndex = array_search($y->color, $referenceArray);
     return $xIndex <=> $yIndex;
});

The idea is: When comparing object $x and object $y, get the index of the colour of $x and $y from $referenceArray and return the comparison of those indices.

apokryfos
  • 30,388
  • 6
  • 55
  • 83