-1

I have a Json array the following values:

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

And I would like to get this array only:

[small, medium, large]

Well, each values use only once in the second array from the first one.

        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"}]
Atti
  • 33
  • 1
  • 8

3 Answers3

1

Your given json format is not correct. I created an example for your better understanding :-

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

Output:-https://eval.in/393669

Note:- I have taken your json format. modified it to be correct and make example for that. It will be easy to understand i hope. thanks.

Based on your latest json format edit, here the link, which ave proper answer for that:-

https://eval.in/393680

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

You can combine array_column to extract the value of size, then run array_unique on it.

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

If you want you can then get the original array with all keys but with just the unique sizes.

$uniques = array_intersect_key($json_array, $size_array);
OIS
  • 9,833
  • 3
  • 32
  • 41
0

if your version of php does not have function 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);

result

Array
( 
  [0] => Array ( [size] => small )
  [2] => Array ( [size] => medium )
  [4] => Array ( [size] => large )
)
splash58
  • 26,043
  • 3
  • 22
  • 34