重建json数据以删除一个子节点中的重复值 [英] Rebuild a json data remove duplicate value in one child node

查看:105
本文介绍了重建json数据以删除一个子节点中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些json数据:

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"
]

我要删除子节点"a"中的所有重复值(保留第一个出现的值).

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

输出=>

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

推荐答案

这已通过测试,并且可以按照您的描述运行:

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

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

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.

这篇关于重建json数据以删除一个子节点中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆