user1464137
user1464137

Reputation: 15

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

I’m attempting to use the values from one JSON link to populate values in other JSON links resulting in a unique list of values from the combined JSON. I’ve gotten as far as creating the complete list of values, but I’m having a difficult time finding the syntax in the final loop to display only the unique values. Any help would be appreciated.

$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
     }

}

Working code:

$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>';
}

Upvotes: 0

Views: 4550

Answers (1)

Sliq
Sliq

Reputation: 16494

Simply change this

$object_array [] = array_unique($object);

to that

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

Maybe you can also do this with one line of code, but I dont know how to write it. But the way the way I wrote it it's a little bit unoptimized, it would be better to simply do the array_unique() only one time, right after the final loop.

Btw your problem is/was that you tried to make $object unique, which is not an array. it's a string/object.

Upvotes: 2

Related Questions