sorting - I need to sort by price, and then by time for identical prices multidimensional associated array -
i need sort price, , things identical prices. have sort price. here array , sort have:
<?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 array: <br>"; foreach ($a $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 price..."; uasort($a, $sortbyprice); printlist($a); ?>
how sort timestamp if prices identical? have been trying change sortbyprice function that. should have 2 sorting functions, or 1 better sorting function? how do this?
why not extend in sortbyprice anon function comparing timestamp if prices equal? such follows:
$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; } };
cheers,
Comments
Post a Comment