我有一个数组:
[
{"key": 1, "title": "Animalia", "expanded": true, "folder": true, "children": [
{"key": 2, "title": "Chordate", "folder": true, "children": [
{"key": 3, "title": "Mammal", "children": [
{"key": 4, "title": "Primate", "children": [
{"key": 5, "title": "Primate", "children": [
]},
{"key": 6, "title": "Carnivora", "children": [
]}
]},
{"key": 7, "title": "Carnivora", "children": [
{"key": 8, "title": "Felidae"}
]}
]}
]}
]}
]我想在数组中循环,当"key“等于指定的数字(比方说5)时,我想插入一个"selected":true key=>value
有这种可能吗?
发布于 2014-12-03 20:45:39
只需使用$myArray = json_decode(JSONString)将JSON字符串设置为有效的PHP数组即可。
然后你可以访问你想要的点,比如array_push($myArray,"myValue")
我需要准确的位置,你想要添加哪种类型的价值,给你一个更好的提示.:-)
与工作代码编辑
您必须对您的JSON结构执行递归搜索,以找到您的值并设置所需的值.我给你写了一个简短的php函数.
正如您所看到的,该函数将使用params并将ready数组返回给您,以便进一步使用它.就像下面描述的那样.
使用示例
$myArray = json_decode($myJSON, true);
$myArray = setSelectedForKey($myArray, "6");
echo(json_encode($myArray));遵循您需要的函数:
function setSelectedForKey($searchArray, $searchKey) {
for ($i = 0; $i < count($searchArray); $i++) {
if ($searchArray[$i]["key"] == $searchKey) {
$searchArray[$i]["selected"] = true;
} else {
if (is_array($searchArray[$i]["children"])) {
$searchArray[$i]["children"] = setSelectedForKey($searchArray[$i]["children"], $searchKey);
}
}
}
return $searchArray;
}https://stackoverflow.com/questions/27276712
复制相似问题