PHP使用cURL获取JSON,排序返回的数组


PHP GET JSON using cURL, sorting returned array

我使用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);

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 ) )

我试图使用ksort并通过Total键升序排序数组。如何对数组进行排序,使总数最大的对象排在第一位,其余的按升序排列?

这应该可以为您工作:

usort($data, function ($a, $b) {
    return $a->Total - $b->Total;
});

注意,如果您想要一个关联数组而不是来自json_decode的对象,那么使用json_decode(..., true)

您有一个对象数组。因此,您需要定义自己的自定义排序规则。您应该使用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;
    }
});