我们正在从API导入JSON。 JSON正在顺利但无序
我们想通过名称字段对JSON文件进行排序,我们使用了uasort,但它似乎没有生效吗?
$url="https://dev-api.ourwebsite.com";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// DUMPING THE JSON
$json=json_decode($result, true);
uasort($json, 'name');
foreach($json as $value) {
$course_name=$value["name"];
}
答案 0 :(得分:1)
usort()(或uasort(),如果需要保留数组的键)是您需要的:
<?php
// mocking some data
$json = [
["name" => "paul"],
["name" => "jeff"],
["name" => "anna"]
];
uasort($json,
// this callable needs to return 1 or -1, depending on how you want it to sort
function($a, $b) {
if($a['name']>$b['name']) {
return 1;
} else {
return -1;
}
});
var_dump($json);
foreach($json as $value) {
$course_name=$value["name"];
echo $course_name."<br>";
}
// output:
array(3) {
[2]=>
array(1) {
["name"]=>
string(4) "anna"
}
[1]=>
array(1) {
["name"]=>
string(4) "jeff"
}
[0]=>
array(1) {
["name"]=>
string(4) "paul"
}
}
anna
jeff
paul