这是一个json树。
[
{"name":"foo"},
{"name":"bar"},
{"name":"Hello"}
]
如何将一个单词放入json树中,以匹配是否存在该单词?这样的:
$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
}
单向:
$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");
}
首先需要使用json_decode将JSON代码转换为有效的PHP数据类型。一旦有了有效的PHP数据类型(例如数组),就可以遍历它的值或使用PHP数组函数之一来搜索它。
如果将其转换为数组,可以像这样轻松地插入新值(与示例保持相同的结构):
$tree[]['name'] = 'Hi';
完成后,使用json_encode获取新树的JSON表示。