Search code examples
phparrayssortingmultidimensional-arrayarray-multisort

Sort a row of a 2d array and apply the same movements to all other rows


I know this question has been asked many times but I have yet to see an array built like this. I have tried some of the numerous examples I have found but none seem to do the trick.

I am editing a PHP program that creates a dropdown list of UPS rates. The functions in this program create an array that is structured like this. I'd like to be able to sort this array on price.

$array = [
    'price' => [
        617.75,
        632.97,
        782.77,
        597.93,
        337.00
    ],
    'option_value' => [
        '07',
        '08',
        '54',
        '65',
        '11'
    ],
    'option_name' => [
        'WorldWide Express',
        'WorldWide Expedited',
        'WorldWide Express Plus',
        'International Saver',
        'International Standard'
    ]
];

Solution

  • For ascending, I would try:

    array_multisort($array['price'], SORT_ASC, $array['option_value'], $array['option_name']);
    

    To go along with the other answer to restructure the array:

    foreach($array['price'] as $key => $value) {
        $result[] = array('price'=>$array['price'][$key],
                          'option_value'=>$array['option_value'][$key],
                          'option_name'=>$array['option_name'][$key]);
    }
    array_multisort(array_column($result, 'price'), SORT_ASC, $result);