1

我需要按价格排序,然后是价格相同的东西。我有按价格排序的。这是我拥有的数组和排序:

<?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 函数,以便它做到这一点。我应该有两个排序功能,还是一个更好的排序功能?我该怎么做呢?

4

1 回答 1

1

为什么不在 sortByPrice 匿名函数中扩展它,以便在价格相等时比较时间戳?如下:

$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;
                   }
            };

干杯,

于 2013-04-18T13:19:34.450 回答