循环遍历 php 数组并在指定位置插入键=>值


Loop through php array and insert key=>value at specified position

我有这个数组:

[
    {"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"}
                ]}
            ]}
        ]}
    ]}
]

我想遍历数组,当"键"等于指定数字(假设 5)时,我想插入一个"选定":真键=>值

有这种可能吗?

好吧,

只需将您的 JSON 字符串转换为有效的 PHP 数组,$myArray = json_decode(JSONString)

然后你可以访问你想要的点,如array_push($myArray[0]["1"],"myValue")

我需要您要添加哪种类型的值的确切位置,以便为您提供更好的提示... :-)

使用工作代码编辑

您必须对 JSON 结构进行递归搜索,以找到您的值并设置您需要的值......我给你写了一个简短的 php 函数来做这个技巧......

如您所见,该函数采用参数并返回准备好的 php 数组以供进一步使用......就像下面描述的那样称呼它....

使用示例

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