我需要按价格排序,然后是相同价格的东西。我有按价格排序的。这是我的数组和排序:
<?php
$a = array(
1 => array('price' => 9.25, 'timestamp_added' => 1301945848, 'name' => 'pencils'),
4 => array('price' => 19.15, 'timestamp_added' => 1299267448, 'name' => 'crayon box'),
15 => array('price' => 4.25, 'timestamp_added' => 1299785848, 'name' => 'markers'),
2 => array('price' => 4.28, 'timestamp_added' => 1299785848, 'name' => 'eraser'),
44 => array('price' => 13.99, 'timestamp_added' => 1299872248, 'name' => 'trapper'),
32 => array('price' => 9.25, 'timestamp_added' => 1299872248, 'name' => 'notebook'),
14 => array('price' => 13.99, 'timestamp_added' => 1301945848, 'name' => 'sharpener'),
5 => array('price' => 15.01, 'timestamp_added' => 1299872248, 'name' => 'calculator'),
60 => array('price' => 15.01, 'timestamp_added' => 1397433600, 'name' => 'calculator'),
70 => array('price' => 15.01, 'timestamp_added' => 1293840000, 'name' => 'calculator'),
80 => array('price' => 15.01, 'timestamp_added' => 1363132800, 'name' => 'calculator')
);
function printList($a) {
echo "<br><br> Printing the array: <br>";
foreach ($a as $key => $value) {
echo "<br /> Product ID $key <b>Price:</b> $" . $value['price'] . " <b>Timestamp:</b> "
. $value['timestamp_added'] . " <b>Name:</b> " . $value['name'] . " <b>Date Added: </b>" . date('M d, Y', $value['timestamp_added']);
}
}
$sortByPrice = function ($a, $b) {
return ($a['price'] >= $b['price']) ? 1 : 0;
};
printList($a);
echo "<br><br>Sorting by price...";
uasort($a, $sortByPrice);
printList($a);
?>
如果价格相同,我如何让它按时间戳排序?我一直在尝试改变sortByPrice函数,以便它这样做。我应该有两个排序函数,还是一个更好的排序函数?我该怎么做呢?
为什么不将其扩展到sortByPrice anon函数中,以便在价格相等时比较时间戳?例如:
$sortByPrice = function ($a, $b) {
if($a['price'] == $b['price']){
return ($a['timestamp_added'] >= $b['timestamp_added']) ? 1 : 0;
}
else{
return ($a['price'] >= $b['price']) ? 1 : 0;
}
};
欢呼,