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"
]
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
cj333
  • 2,547
  • 20
  • 67
  • 110
  • Loop over your input list, collect the `a` values in a comparison array `$already[] = $row["a"];` and only populate the output if there wasn't an entry for `a` before; use `in_array($a, $already)` – mario Aug 03 '13 at 16:09
  • possible duplicate of [php multi-dimensional array remove duplicate](http://stackoverflow.com/questions/1861682/php-multi-dimensional-array-remove-duplicate) – mario Aug 03 '13 at 16:11
  • @mario, i have a bad method, so something like your mentioned `$already[] = $row["a"]` do array_unique(), remove the dumplicate value of `a`, the do another query about original json data, call back `b`. So do you have some smart method? – cj333 Aug 03 '13 at 16:15

1 Answers1

3

This is tested and appears to work as you've described:

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

It outputs [{"a":"abc","b:":"10"},{"a":"abd","b:":"12"},{"a":"abe","b:":"15"},{"a":"abf","b:":"16"},{"a":"abg","b:":"17"}], which I believe matches your desired output.

Nick Coons
  • 3,682
  • 1
  • 19
  • 21