Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

Parse Json key/values of a key's value using JObject using PHP

Please can any help me on this, to remove all keys that have values of N/A, -, or empty strings. If one of the values appear in an array then remove that single item from the array

{
  "name": {
    "first": "Robert",
    "middle": "",
    "last": "Smith"
  },
  "age": 25,
  "DOB": "-",
  "hobbies": [
    "running",
    "coding",
    "-"
  ],
  "education": {
    "highschool": "N/A",
    "college": "Yale"
  }
}

Expecting result would be: { "name": { "first": "Robert", "last": "Smith" }, "age": 25, "hobbies": [ "running", "coding" ], "education": { "highschool": "N/A", "college": "Yale" } }

question from:https://stackoverflow.com/questions/66046413/parse-json-key-values-of-a-keys-value-using-jobject-using-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use following logic to remove elements from your source data:

The recursive function cleanUp() cycles through the data and removes all the entries with values that are set in array $remove

$arr = json_decode($json, true);
$remove = ['N/A', '-','',];
cleanUp($arr, $remove);

function cleanUp(array &$arr, array $remove = [])
{
    foreach($arr as $key => &$value) {
        if(is_array($value)) {
            cleanUp($value, $remove);
        } else {
            if(in_array($value, $remove)) unset($arr[$key]);
        }
    }
}

working demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...