I have an array like the following:
$lista = [
'867Ad2' => [
stock => 2,
nombre => "cosa1",
]
'838sdff2' => [
stock => 4,
nombre => "cosa2",
]
'234hsd4fd' => [
stock => 6,
nombre => "cosa3",
]
'8691240654d' => [
stock => 8,
nombre => "cosa4",
]
]
I order it as I want, by the value of the key 'stock'
in this way:
function orderBy($data, $field)
{
$code = "return strnatcmp(\$b['$field'], \$a['$field']);";
sort($data, create_function('$a,$b', $code));
return $data;
}
$sorted_data = orderBy($lista, 'stock');
However, I have noticed that when ordering it, it replaces the indices in the following way:
$lista = [
'0' => [
stock => 8,
nombre => "cosa4",
]
'1' => [
stock => 6,
nombre => "cosa3",
]
'2' => [
stock => 4,
nombre => "cosa2",
]
'3' => [
stock => 2,
nombre => "cosa1",
]
]
That is, it replaces my indexes, which are codes with letters and numbers, for a numerical index.
First, by using
create_function
implicitly you are usingeval
, which is a deprecated practice. Quoting the documentation :Second, what you want to do, to keep the indices while sorting by an arbitrary function, can be done with uasort , and use an anonymous function:
output is
uasort
pass the array by reference, so your original array is mutated. You don't need to capture the sorted array into a new array.I leave you a working fiddle .
PS: Inside your anonymous function you can perfectly well use
strnatcmp
My answer used a more rudimentary version of comparison just so you understand how this closure works internally. It would be useful for example if you wanted to compare by a second field in case it
stock
was the same.