2

Here is some json data:

[
  {"a":"abc","b:":"10"},//"a":"abc"
  {"a":"abd","b:":"12"},
  {"a":"abc","b:":"14"},//"a":"abc"
  {"a":"abe","b:":"15"},
  {"a":"abf","b:":"16"},
  {"a":"abg","b:":"17"},//"a":"abg"
  {"a":"abg","b:":"19"}//"a":"abg"
]

I want remove all the duplicate values in the child node "a" (remain the first appear one).

Output =>

[
  {"a":"abc","b:":"10"},//first appear "a":"abc"
  {"a":"abd","b:":"12"},
  {"a":"abe","b:":"15"},
  {"a":"abf","b:":"16"},
  {"a":"abg","b:":"17"}//first appear "a":"abg"
]
4

1 回答 1

3

这是经过测试的,似乎可以按照您的描述工作:

$json = <<<JSON
[
{"a":"abc","b:":"10"},
{"a":"abd","b:":"12"},
{"a":"abc","b:":"14"},
{"a":"abe","b:":"15"},
{"a":"abf","b:":"16"},
{"a":"abg","b:":"17"},
{"a":"abg","b:":"19"}
]
JSON;

$json_array = json_decode( $json, TRUE );

$new_array = array();
$exists    = array();
foreach( $json_array as $element ) {
    if( !in_array( $element['a'], $exists )) {
        $new_array[] = $element;
        $exists[]    = $element['a'];
    }
}

print json_encode( $new_array );

它输出[{"a":"abc","b:":"10"},{"a":"abd","b:":"12"},{"a":"abe","b:":"15"},{"a":"abf","b:":"16"},{"a":"abg","b:":"17"}],我相信它与您想要的输出相匹配。

于 2013-08-03T16:18:48.453 回答