在 foreach 循环中对 JSON 结果进行排序


sort json results in foreach loop

我正在运行一个foreach循环来显示json结果,当满足某些条件时,并希望按name字段对它们进行排序。我正在尝试usort(),但似乎无法弄清楚。

杰森:

{
    "Shawn Taylor":{
        "name":"Shawn Taylor",
        "title":"",
        "photo_url":"house_165 (1).jpg",
        },
    "Another Name": {
        "name":"Another Name",
        "title":"Title is here",
        "photo_url":"Person.jpg",
        }
}

.PHP:

$data_json = file_get_contents('data.json');
$data_array = json_decode($data_json, true);
$i = 0;
foreach($data_array as $key => $person){
  if($person['title'] == 'some title'){
    include('card.php'); 
    if(++$i % 4 === 0) {
      echo '<div class="clearfix"></div>'; // inserts a clearfix every 4 cards
    }
  }
}

因此,这将返回我期望的所有结果,但未排序。我已经尝试了几种不同的方式 usort(),但只是非常糟糕地摔倒在我的脸上:)请帮忙!

首先

使用json_decode转换为php数组,将标志设置为TRUE表示关联数组$myarr = json_decode($array, TRUE)尝试自定义 usort

 // Sort the multidimensional array
 usort($myarr, "custom_sort");
 // Define the custom sort function
 function custom_sort($a,$b) {
      return $a['name']>$b['name'];
 }

我希望这有所帮助。

您的 json 格式不正确。有几个额外的逗号,每个JPG项目后面一个。在下面删除。

然后,将 json 字符串json_decode为 PHP 关联数组,并且由于您将名称用作 json 索引,因此ksort(键排序)生成的数组。

$json_string = '{
    "Shawn Taylor":{
        "name":"Shawn Taylor",
        "title":"",
        "photo_url":"house_165 (1).jpg"
        },
    "Another Name": {
        "name":"Another Name",
        "title":"Title is here",
        "photo_url":"Person.jpg"
        }
}';
$data_array = json_decode($json_string, true);
ksort($data_array);
// the remaining code

ksort后显示print_r

Array
(
    [Another Name] => Array
        (
            [name] => Another Name
            [title] => Title is here
            [photo_url] => Person.jpg
        )
    [Shawn Taylor] => Array
        (
            [name] => Shawn Taylor
            [title] => 
            [photo_url] => house_165 (1).jpg
        )
)

如果需要按嵌套索引排序,并且想要维护关联数组,请使用 uasort

uasort($data_array, 'sort_name_index');
function sort_name_index($a, $b) {
  return $a['name'] > $b['name'];
}