[英]sort json results in foreach loop
當滿足某些條件時,我正在運行一個foreach循環以顯示json結果,並想按name
字段對它們進行排序。 我正在嘗試usort()
,但似乎無法弄清楚。
JSON:
{
"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格式不正確。 還有幾個逗號,每個JPG項目后一個。 在下面刪除。
然后, json_decode
將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
甲print_r
后ksort
顯示:
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'];
}
首先使用json_decode轉換為php數組,將關聯數組$myarr = json_decode($array, TRUE)
的標志設置為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'];
}
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.