fish man
fish man

Reputation: 2700

php json decode ingnore duplicate value

Php json decode, how to ingore duplicate value? in my case, if $data->a and $data->b are duplicate, only print the first appear value.

[
{"a":"1","b":"2","c":"content1"},
{"a":"1","b":"3","c":"content2"},//print
{"a":"1","b":"3","c":"content3"},//duplicate "a":"1","b":"3", do not print
{"a":"2","b":"1","c":"content4"},
{"a":"2","b":"2","c":"content5"},//print
{"a":"2","b":"2","c":"content6"},//duplicate "a":"2","b":"2", do not print
{"a":"2","b":"3","c":"content7"}
]

This is not an easy array_unique() could work, ask for a help, thanks.

Upvotes: 0

Views: 229

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65274

Use a hash array!

$tmp=json_decode($input);
$data=array();
foreach ($tmp as $item) {
  $idx=$item->a."::".$item->b;
  if (!isset($data[$idx])) $data[$idx]=$item;
}
$data=array_values($data);

Upvotes: 3

Related Questions