1

I have the following array:

$data['array'] = array(
    1 => array(
        'currency_name' => 'USD',
        'totals' => '310.00 USD'
    ),
    24 => array(
        'currency_name' => 'EUR',
        'totals' => '200.00 EUR'
    ),
    26 => array(
        'currency_name' => 'GBP',
        'totals' => '100.00 GBP'
    )
);

I wanted to be sorted by currency_name key and I used the following function:

// sort the array by currency_name key
$sort = array();
foreach ($data['array'] as $i => $row)
{
    $sort[$i] = $row['currency_name'];
}
array_multisort($sort, SORT_NATURAL, $data['array']);

Output:

Array
(
    [array] => Array
        (
            [0] => Array
                (
                    [currency_name] => EUR
                    [totals] => 200.00 EUR
                )

            [1] => Array
                (
                    [currency_name] => GBP
                    [totals] => 100.00 GBP
                )

            [2] => Array
                (
                    [currency_name] => USD
                    [totals] => 310.00 USD
                )

        )

)

Expected:

Array
(
    [array] => Array
        (
            [24] => Array
                (
                    [currency_name] => EUR
                    [totals] => 200.00 EUR
                )

            [26] => Array
                (
                    [currency_name] => GBP
                    [totals] => 100.00 GBP
                )

            [1] => Array
                (
                    [currency_name] => USD
                    [totals] => 310.00 USD
                )

        )

)

This is reindexing the array, which I don't want. I need those keys later on.

Note:
* The method I've used above was this
* I need SORT_NATURAL as I use this function for other strings too.

Community
  • 1
  • 1
machineaddict
  • 3,216
  • 8
  • 37
  • 61

2 Answers2

7

As you can read from array_multisort documentation, only associative (string) keys are preserved. You can use uasort instead.

uasort($data['array'], function($a, $b) {
    return strnatcmp($a['currency_name'], $b['currency_name']);
});
pNre
  • 5,376
  • 2
  • 22
  • 27
1

You can try natcasesort($array) function. This function sort an array using a case insensitive "natural order" algorithm.It returns TRUE on success or FALSE on failure.

Rishabh
  • 167
  • 2
  • 13