phparrayssortingassociative-arraycustom-sort

Sort an associative array with unique values by the values of another indexed array


I have 2 arrays:

[
    'field_bathrooms' => 'Bathrooms',
    'field_bedrooms' => 'Bedrooms',
    'field_king_beds' => 'King Beds',
    'field_kitchen' => 'Kitchen',
    'field_queen_beds' => 'Queen Beds',
    'field_sleeps_max' => 'Sleeps',
    'field_sofa_beds' => 'Sofa Beds',
    'field_sqft' => 'Square Footage',
    'field_twin_beds' => 'Twin Beds',
]

My preferred order:

[
    'Bathrooms',
    'Square Footage',
    'King Beds',
    'Sofa Beds',
    'Sleeps',
    'Twin Beds',
    'Queen Beds',
    'Kitchen',
    'Bedrooms',
]

I want to sort the 1st array by the 2nd array's key, so final result is an array like this:

[
    'field_bathrooms' => 'Bathrooms',
    'field_sqft' => 'Square Footage',
    'field_king_beds' => 'King Beds',
    'field_sofa_beds' => 'Sofa Beds',
    'field_sleeps_max' => 'Sleeps',
    'field_twin_beds' => 'Twin Beds',
    'field_queen_beds' => 'Queen Beds',
    'field_kitchen' => 'Kitchen',
    'field_bedrooms' => 'Bedrooms',
]

Solution

  • This will do what you want in one line:

    $result = array_flip( array_replace( array_flip($arr2), array_flip($arr1) ) );
    
    print_r($result);
    

    To explain: Since you want to sort by the value in the array, and not by the key, we use array_flip to flip the array and value in each of your arrays. Then, we use array_replace to replace the values in the second array with the matching ones from the first array (keeping the current order). Then we use array_flip to put the keys and values back how we started.