所有
我有数组格式的以下数组。显示JSON格式只是为了方便用户使用。如何在php中使用键“name”对数组进行升序排序?
"food":
[
{
"id": 1,
"name": "dessert"
},
{
"id": 2,
"name": "maincourse"
},
{
"id": 3,
"name": "entrees"
},
{
"id": 4,
"name": "appetizers"
}
]
所需的结果是这样的数组:
"food":
[
{
"id": 4,
"name": "appetizers"
},
{
"id": 1,
"name": "dessert"
},
{
"id": 3,
"name": "entrees"
},
{
"id": 2,
"name": "maincourse"
}
]
答案 0 :(得分:5)
使用usort()
:
$array = array('food' => array(
array(
"id"=> 1,
"name"=> "dessert"
),
array(
"id"=> 2,
"name"=> "maincourse"
),
array(
"id"=> 3,
"name"=> "entrees"
),
array(
"id"=> 4,
"name"=> "appetizers"
)
)
);
function compare($a, $b) {
return strcmp($a['name'], $b['name']);
}
usort($array['food'], 'compare');
print_r($array);
答案 1 :(得分:0)
您可以使用ksort()函数(php.net/ksort)
ksort($array);
例如,如果你有一个数组:
$array = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($array);
它会将它们分类为a,b,c,d。