user1043646
user1043646

Reputation:

PHP Sort array by position in associative array

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

Upvotes: 2

Views: 101

Answers (1)

apokryfos
apokryfos

Reputation: 40680

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.

Upvotes: 1

Related Questions