值在JSON的数组中使用一次

时间:2015-07-06 19:40:39

标签: php arrays json foreach

我有一个Json数组有以下值:

[small, medium, small, large, medium, medium, large, small]

我只想获得这个数组:

[small, medium, large]

好吧,每个值在第一个数组的第二个数组中只使用一次。

        foreach($json_array as $json_arr){ 
            if (!isset($size_array)) {
                $size_array = array();
            }   

            foreach($size_array as $s_a) {
                if ($s_a != $json_arr['size']) {
                    $x = true;
                } 
            }

            $size_array[] = $json_arr['size'];

        }               

        echo "<br><br><br>";
        foreach($size_array as $s_a) {
            echo $s_a;
        }


[{"size":"small"},{"size":"small"},{"size":"medium"},{"size":"medium"},{"size":"large"},{"size":"small"},{"size":"large"},{"size":"large"},{"size":"large"}]

3 个答案:

答案 0 :(得分:1)

您的json格式不正确。我为您提供了一个更好理解的例子: -

<?php 
$json = '{"0":"small","1":"medium","2":"small","3":"large","4":"medium","5":"medium","6":"large","7":"small"}';
$new_array = json_decode($json);
$common_array = array();
foreach($new_array as $new_arr){
    $common_array[] = $new_arr;
}
echo "<pre/>";print_r($common_array);
echo "<pre/>";print_r(array_unique($common_array));
?>

输出: - https://eval.in/393669

注意: - 我采用了你的json格式。将其修改为正确并为此做出示例。我希望这很容易理解。谢谢。

根据您最新的json格式编辑,这里是链接,正确答案: -

https://eval.in/393680

答案 1 :(得分:0)

您可以组合array_column来提取size的值,然后在其上运行array_unique。

$size_array = array_unique(array_column($json_array, "size"));

如果你想要,你可以使用所有键获得原始数组,但只有唯一的大小。

$uniques = array_intersect_key($json_array, $size_array);

答案 2 :(得分:0)

如果你的php版本没有函数array_column

$str = '[{"size":"small"},{"size":"small"},{"size":"medium"},{"size":"medium"},{"size":"large"},{"size":"small"},{"size":"large"},{"size":"large"},{"size":"large"}]';

$json_array = json_decode($str, true);
$ss = array();   // list of sizes. Realy it is the result too 
                 // but array has structure  as [ smal, medium, large ]
$new = array_filter($json_array, 
              function ($item) use (&$ss) {
                 if (in_array($item['size'], $ss)) return false;
                 else { $ss[] = $item['size'];}
                 return true;
              } );             
print_r($new);

结果

Array
( 
  [0] => Array ( [size] => small )
  [2] => Array ( [size] => medium )
  [4] => Array ( [size] => large )
)