如何在 PHP 中返回基于 JSON 结果的唯一列表


How do I return a unique list based on JSON results in PHP?

我正在尝试使用一个 JSON 链接中的值来填充其他 JSON 链接中的值,从而从组合的 JSON 中生成唯一的值列表。 我已经创建了完整的值列表,但是我很难在最终循环中找到语法以仅显示唯一值。 任何帮助将不胜感激。

$collection_string = file_get_contents("http://some_json_url.com/json");
$collection_list = json_decode($collection_string, true);
foreach ($collection_list as $col_lists => $col_list) {
     $object_string = file_get_contents('http://another_json_url.com/'.$col_list['key'].'/json');
     $object_list = json_decode($object_string, true);
     $object_array = array();
     foreach ($object_list as $objects => $object) {
          $object_array [] = array_unique($object); //Returns "Warning: array_unique() expects parameter 1 to be array, string given in..."
          echo '<li><a href="some_search_url/'.$object_array.'/search/">'.$object_array.'</a></li>'; //Returns "Array"
          echo '<li><a href="some_search_url/'.$object.'/search/">'.$object.'</a></li>'; //Returns complete list
     }
}

工作代码:

$collection_string = file_get_contents("http://some_json_url.com/json");
$collection_list = json_decode($collection_string, true);
$object_array = array();
foreach ($collection_list as $col_lists => $col_list) {
     $object_string = file_get_contents('http://another_json_url.com/'.$col_list['key'].'/json');
     $object_list = json_decode($object_string, true);
     foreach ($object_list as $key => $value) {
          array_push($object_array, $value);
     }
}
$object_unique = array_unique($object_array);
natcasesort($object_unique);
foreach ($object_unique as $key => $value) {
     echo '<li><a href="some_search_url/'.$value.'/search/">'.$value.'</a></li>';
}

只需更改此内容

$object_array [] = array_unique($object);

到那个

$object_array [] = $object; // edited !
array_unique($object_array);

也许你也可以用一行代码来做到这一点,但我不知道怎么写。但是我编写它的方式有点未优化,最好只做一次 array_unique(),就在最后一个循环之后。

顺便说一句,你的问题是/曾经你试图使$object唯一,这不是一个数组。 它是一个字符串/对象。