Domanda

I want to sort a multidimensional array. With only one key it's no problem at all.

$value1 = array();
foreach ($dataArray as $key => $row)
{
    $value1[$key] = $row['value_a'];
}
array_multisort($value1, SORT_ASC, $dataArray);

Now I want to sort the above array with two values, value_a and value_b and weight value_a 1.5 times. value_a is a distance e.g. 300 feet and value_b is a price e.g. 450. Just to give you some context...

array_multisort is able to sort an array based on two values but not weighting them differently.

Any help would be highly appreciated :)

Thanks a lot for your effort!

È stato utile?

Soluzione

I'd use usort, which takes a callback so you can define any comparison behaviour you like.

In your case, something like:

usort($value1, function($a, $b) {
    return $a['value_a'] * 1.5 + $a['value_b'] - $b['value_a'] * 1.5 - $b['value_b'];
});

http://www.php.net/manual/en/function.usort.php

Update: There is a note on the above manual page that the result of the callback will be rounded to an integer, therefore you might want to consider your own rounding within the callback (e.g. if the amounts are dollars you could multiply everything by 100 to get an integer value)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top