PHP使用cURL获取JSON,对返回的数组进行排序
我使用PHP从web服务返回JSON。我能够获取JSON,解码它,并查看结果。但是,我需要能够按特定值对数组进行排序。我目前有:PHP使用cURL获取JSON,对返回的数组进行排序,php,json,curl,Php,Json,Curl,我使用PHP从web服务返回JSON。我能够获取JSON,解码它,并查看结果。但是,我需要能够按特定值对数组进行排序。我目前有: // JSON URL which should be requested $json_url = 'https://*******/maincategories'; // Initializing curl $ch = curl_init( $json_url ); // Configuring curl options $options = array( CU
// JSON URL which should be requested
$json_url = 'https://*******/maincategories';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
$data = json_decode($result);
ksort($data, "Total");
print_r($data);
打印($data)代码>打印此文件:
Array ( [0] => stdClass Object ( [Goal] => 10000000 [Name] => Rental [Total] => 500000 ) [1] => stdClass Object ( [Goal] => 8000000 [Name] => National Sales [Total] => 750000 ) [2] => stdClass Object ( [Goal] => 120000000 [Name] => Vendor Leasing [Total] => 500000 ) )
我试图使用ksort并通过Total
键按升序对数组进行排序。如何对该数组进行排序,使总数最高的对象排在第一位,其余的按升序排列?您有一个对象数组。因此,您需要定义自己的自定义排序规则。您应该为此使用usort()
。也许是这样的:
usort($data, function ($a, $b) {
if ((int)$a->Total > (int)$b->Total)) {
return 1;
} else if ((int)$a->Total < (int)$b->Total)) {
return -1;
} else {
return 0;
}
});
usort($data,function($a,$b){
如果((int)$a->Total>(int)$b->Total)){
返回1;
}否则如果((int)$a->总计<(int)$b->总计)){
返回-1;
}否则{
返回0;
}
});
这应该适合您:
usort($data, function ($a, $b) {
return $a->Total - $b->Total;
});
请注意,如果您想要一个关联数组而不是json\u decode
中的对象,那么使用json\u decode(…,true)
ksort()在多维数组上不起作用,这基本上就是您所拥有的。