PHP print out only unique values from array

2019-09-07 12:10发布

问题:

I'm hoping someone can help me with a problem I am having returning only unique values from an array.

I am pulling data from the 500px API of photographs that I have favourited. From this array I would like to pull out the category IDs of the photos. The below does the job to a certain extent, but I want to show only unique values (ultimately I want to build a navigation from the labels associated with the IDs).

if($json){
        $obj = json_decode($json); 
                }
      else {
        print "<p>Currently, No Service Available.</p>";
            } 


            foreach ($obj->photos as $photo){


        print $photo->category;

           } 

This just returns a string 99241210812231382611121281221121812. These are the correct category IDs of the photos I have favourited however I would like to show 9, 1, 2 etc only once.

I've spent some time on the PHP manual and on here and have tried the below

if($json){
        $obj = json_decode($json); 
                }
      else {
        print "<p>Currently, No Service Available.</p>";
            } 


            foreach ($obj->photos as $photo){
              $test=$photo->category;
             $unique=str_split($test);
print array_unique($unique);

           }

But this just returns a sting ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

If I try:

foreach ($obj->photos as $photo){

print array_unique($photo->category);

           }

I get Warning: array_unique() [function.array-unique]: The argument should be an array. Any help would be much appreciated!

回答1:

Set an array to store the categories. Fill it with category ids. Make it hold only unique values. Echo it.

$categories=array();
foreach ($obj->photos as $photo){
    $categories[]=$photo->category;
}
$categories=array_unique($categories);

print implode(', ', $categories); // will show a string 9, 1, 2

print_r($categories); // will show the values as an array 
                      // you may want to view page source to read them easily

http://uk3.php.net/function.implode
http://uk1.php.net/print_r

Another way to do this is by setting array keys $categories[$photo->category]=true; and then using array_keys().