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

2
  • 1
    See php.net/array-multisort Commented Dec 10, 2018 at 10:31
  • 1
    Basically answered in stackoverflow.com/a/17364128/476, under Sorting into a manual, static order. Do you have any specific problems applying that here? Commented Dec 10, 2018 at 10:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments