Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按JSON排序_Php_Json - Fatal编程技术网

Php 按JSON排序

Php 按JSON排序,php,json,Php,Json,我们正在从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 pri

我们正在从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"];


}
(或者如果您需要保留阵列的密钥)是您需要的:

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

选择其中一个选项。(usort可能是最好的选择)嗨,杰夫,谢谢,我们确实尝试过uasort,但它似乎对结果没有影响。“名称”不是一个函数/可调用的(至少这里没有显示),所以它不会有效果。下面介绍如何使用uasort。