2016-05-25 150 views
0

如何合并两个JSON arrays,然后对ID的值进行排序,以便结果显示最高的数字到最低的数字?合并两个JSON数组,然后对它们进行排序

例如,从脚本我的期望的输出下面将是:

  • 1 - 神保
  • 2 - 鲍勃
  • 6 - 卢克
  • 12 - 克里斯
  • 16 - 乔纳斯
  • 36 - 山姆

这里是我的JSON数组:

$json1 =' 
{ 
    "error": "trueee", 
    "info": { 
     "collections": [{ 
      "ID": "1" 
      "Name": "Jimbo" 
     }, { 
      "ID": "36" 
      "Name": "Sam" 
     }, { 
      "ID": "2", 
      "Name": "Bob" 
     }] 
    } 
} 
'; 

$json2 =' 
{ 
    "error": "trueee", 
    "info": { 
     "collections": [{ 
      "ID": "12" 
      "Name": "Chris" 
     }, { 
      "ID": "6" 
      "Name": "Luke" 
     }, { 
      "ID": "16" 
      "Name": "Jonas" 
     }] 
    } 
} 
'; 

回答

1

您需要从JSON字符串merge阵列。首先用关联数组获取arr的json解码比使用array_column得到ID列后,你需要合并两个数组并最终对它们进行排序。

Online CheckLong Conversation

$json1 =' 
{ 
    "error": "trueee", 
    "info": { 
     "collections": [{ 
      "ID": "1" 
     }, { 
      "ID": "36" 
     }, { 
      "ID": "2" 
     }] 
    } 
} 
'; 

$json2 =' 
{ 
    "error": "trueee", 
    "info": { 
     "collections": [{ 
      "ID": "12" 
     }, { 
      "ID": "6" 
     }, { 
      "ID": "16" 
     }] 
    } 
} 
'; 

$arr1 = json_decode($json1, true); 
$arr2 = json_decode($json2, true); 

$arr1 = array_column($arr1['info']['collections'], "ID"); 
$arr2 = array_column($arr2['info']['collections'], "ID"); 

$arr = array_merge($arr1, $arr2); 
sort($arr); 
echo '<pre>'; 
print_r($arr); 

结果:

Array 
(
    [0] => 1 
    [1] => 2 
    [2] => 6 
    [3] => 12 
    [4] => 16 
    [5] => 36 
) 
+0

你改变了你的问题,而我的回答... –

+0

哪个while循环??? –

+0

我让我的答案从json字符串,循环需要一些验证检查? –

相关问题