我使用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(
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);
Run Code Online (Sandbox Code Playgroud)
这print_r($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 ) )
Run Code Online (Sandbox Code Playgroud)
我试图使用ksort并通过Total密钥按升序对数组进行排序.如何对此数组进行排序,以使总数最高的对象成为第一个,其余的按升序排列?
这应该适合你:
usort($data, function ($a, $b) {
return $a->Total - $b->Total;
});
Run Code Online (Sandbox Code Playgroud)
请注意,如果您想要关联数组而不是对象json_decode,请使用json_decode(..., true)
| 归档时间: |
|
| 查看次数: |
8082 次 |
| 最近记录: |