如果单词存在,如何将一个单词放入json树中?

时间:2011-07-19 22:08:24

标签: php json

这是一张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
}

2 个答案:

答案 0 :(得分:2)

一种方式:

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

答案 1 :(得分:1)

首先,您需要使用 json_decode 将JSON代码转换为有效的PHP数据类型。一旦拥有了有效的PHP数据类型(例如数组),您就可以遍历其值或使用PHP数组函数之一进行搜索。

如果将其转换为数组,则可以轻松插入这样的新值(保持示例的结构相同):

$tree[]['name'] = 'Hi';

完成后,使用 json_encode 获取新树的JSON表示。