【问题标题】:How can we custom sort the data in a Multi-Dimentional Array [duplicate]我们如何自定义对多维数组中的数据进行排序[重复]
【发布时间】:2012-01-08 13:36:27
【问题描述】:

可能重复:
How do I sort a multidimensional array by one of the fields of the inner array in PHP?

我想知道,我们如何自定义排序多维数组。该数组包含以下值:-

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

在第一个数组中,John 是名称,155 是 ID,10 是价格。如何按价格(从最高到最低)对整个数组进行排序,然后使用foreach 循环打印数据?

【问题讨论】:

    标签: php arrays sorting


    【解决方案1】:

    你可以定义比较函数,并使用'usort'方法。

    见下面的例子。

    <?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]. "\n";
    }
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-07-18
      • 2017-06-07
      • 2014-04-01
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多