How to put one word into a json tree, if the word exist?
Here is a json tree.
[
{"name":"foo"},
{"name":"bar"},
{"name":"Hello"}
]
开发者_如何转开发How to put one word into a json tree, to match if the word exist? like this:
$word = 'foo'; //'title'
if(...){
//if 'foo' is exist in the json tree, do some stuff
} else{
//if 'title' is not exist in the json tree, do something here
}
One way:
$word = 'foo';
$data = json_decode($tree);
$found = false;
foreach($tree as $element) {
if ($element['name'] == $word) {
$found = true;
break;
}
}
if (!$found) {
die("Word not found");
}
First your need to convert the JSON code to a valid PHP data type using json_decode. Once you have a valid PHP data type, like an array for instance, you will be able to loop through its values or use one of PHP array functions to search it.
If you transform it into an array, you can easily insert new values like this (keeping the same structure of your example):
$tree[]['name'] = 'Hi';
Once you are done, use json_encode to get a JSON representation of your new tree.
精彩评论