如何在php中对多维关联数组进行排序

时间:2014-05-14 08:20:33

标签: php cakephp-2.3

我有一个如下所示的数组。我想使用最大价格值对这个多维关联数组进行排序。

<?php
    $car = array
        (
        '0' =>
        array('RoomType' => array
                (
                'price' => array(
                    'max_price' => '200'
                )
            )
        ),
        '1' =>
        array('RoomType' => array
                (
                'price' => array(
                    'max_price' => '400'
                )
            )
        )
    );
    ?>

你可以帮我解决这个问题吗?在此先感谢。

1 个答案:

答案 0 :(得分:3)

您可以使用array_multisort()按价格对其进行排序。考虑这个例子:

$cars = array (
    '0' => array(
        'RoomType' => array (
            'price'=> array('max_price' => '200' )
    )
),
'1' => array(
    'RoomType' => array (
        'price'=> array( 'max_price' => '400' )
    )
),
'2' => array(
    'RoomType' => array (
        'price'=> array( 'max_price' => '100' )
    )
),
'3' => array(
    'RoomType' => array (
        'price'=> array( 'max_price' => '50' )
    )
)
);

$price = array();
foreach($cars as $key=> $value) {
    $price[] = $value['RoomType']['price']['max_price'];
}

// for ascending use SORT_ASC 
// for descending, use SORT_DESC
array_multisort($price, SORT_ASC, $cars);

print_r($cars);

示例输出:

 Array
 (
     [0] => Array
         (
             [RoomType] => Array
                 (
                     [price] => Array
                         (
                             [max_price] => 50
                         )

                 )

         )

     [1] => Array
         (
             [RoomType] => Array
                 (
                     [price] => Array
                         (
                             [max_price] => 100
                         )

                 )

         )

     [2] => Array
         (
             [RoomType] => Array
                 (
                     [price] => Array
                         (
                             [max_price] => 200
                         )

                 )

         )

     [3] => Array
         (
             [RoomType] => Array
                 (
                     [price] => Array
                         (
                             [max_price] => 400
                         )

                 )

         )

 )