2013-05-20 18 views
0

PHP JSON解碼,如何ingore重複值?在我的情況下,如果$data->a$data->b是重複的,只打印第一個出現的值。PHP JSON解碼ingnore重複值

[ 
{"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"} 
] 

這不是一件容易的array_unique()可以工作,請求幫助,謝謝。

+0

看一看http://www.php.net/array_filter – migg

回答

3

使用散列數組!

$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); 
+0

感謝的,它的工作原理,但對於'($ TMP爲$項目){'應該'的foreach($ TMP爲$項) {' –

+0

謝謝,更新了答案中的代碼! –