0

我希望有人可以帮助我解决我只从数组中返回唯一值的问题。

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

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


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


        print $photo->category;

           } 

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

我在 PHP 手册和这里花了一些时间,并尝试了以下

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

           }

但这只会返回一个刺痛的 ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

如果我尝试:

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

print array_unique($photo->category);

           }

我收到警告:array_unique() [function.array-unique]:参数应该是一个数组。任何帮助将非常感激!

4

1 回答 1

1

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

$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().

于 2014-01-09T22:08:27.403 回答