PHP仅从数组中打印出唯一值 [英] PHP print out only unique values from array

查看:114
本文介绍了PHP仅从数组中打印出唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以解决我仅从数组返回唯一值的问题.

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

我正在从我喜欢的照片的500px API中提取数据.我想从这个数组中提取照片的类别ID.下面在一定程度上完成了这项工作,但是我只想显示唯一值(最终我想从与ID关联的标签构建导航).

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;

           } 

这只是返回一个字符串99241210812231382612611121281221121812.这些是我收藏的照片的正确类别ID,但是我只想显示9、1、2等一次.

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.

我花了一些时间在PHP手册和此处,并尝试了以下内容

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);

           }

但这只会返回一个字符串ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

But this just returns a sting ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

如果我尝试:

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

print array_unique($photo->category);

           }

我得到警告:array_unique()[function.array-unique]:参数应为数组.任何帮助将不胜感激!

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

推荐答案

设置一个数组来存储类别.用类别ID填充它.使它仅包含唯一值.回声.

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

另一种方法是设置数组键$categories[$photo->category]=true;,然后使用array_keys().

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

这篇关于PHP仅从数组中打印出唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆