douwei4370 2011-11-29 06:49
浏览 33
已采纳

我们如何在多维数组中自定义数据排序[重复]

Possible Duplicate:
How do I sort a multidimensional array by one of the fields of the inner array in PHP?

I would like to know, how can we custom sort a multi-dimentional array. The array contains values like:-

$products = array(
    array('John', '155', 10 ),
    array( 'Paul', '151', 95 ),
    array( 'Rodger', '152', 85 )
);

In the first array, John is the name, 155 is the ID and 10 is the Price. How can I sort the whole array by Price(Highest to Lowest) and then print the data using a foreach loop?

  • 写回答

1条回答 默认 最新

  • drf65218 2011-11-29 07:05
    关注

    you can define compare function, and use 'usort' method.

    see below example.

    <?php
    
    // Comparison function
    function cmp($a, $b) {
        if ($a[2] == $b[2]) {
            return 0;
        }
        return ($a[2] < $b[2]) ? -1 : 1;
    }
    
    // Array to be sorted
    $products = array( array( 'John', '155', 10 ),
          array( 'Paul', '151', 95 ),
          array( 'Rodger', '152', 85 ) );
    
    // Sort array
    usort($products, 'cmp');
    
    //Print the resulting array
    foreach ($products as $key=>$item) {
        echo "Name : ".$item[0]. "  ID : " .$item[1]. "  Price : ".$item[2]. "
    ";
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?