phpsortingmultidimensional-arrayforeachassociative-array

I need to sort by price, and then by time for identical prices multidimensional associated array


I need to sort by price, and then for things with identical prices. I have the sort by price. Here is the array and sort that I 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 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);
        ?>

How do I get it to sort by the timestamp if the prices are identical? I have been trying to change the sortByPrice function so that it does that. Should I have two sorting functions, or one better sorting function? How do I do this?


Solution

  • Why not just extend it in the sortByPrice anon function so that you are comparing the timestamp if the prices are equal? Such as 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,