微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在PHP的多维数组中附加新的键和值字段?

如何解决如何在PHP的多维数组中附加新的键和值字段?

我有一个以下格式的数组。 示例Json供参考: https://jsoneditoronline.org/#left=cloud.42c7485653ea40549da90cf4338f8b23

我想在每个childData数组中添加“ super_parent_id”。 因此,如果childData存在,我需要将super_parent_id附加到该子数组。同样,如果子数组中存在childData数组,则需要在该子数组后附加super_parent_id。

我认为递归可以解决此问题,但是我不确定该怎么做。 谢谢。

解决方法

是的,正确的,递归是解决问题的方法之一。这是一个代码片段,说明如何实现这种数据结构的递归修改。

function appendSuperParentId(&$elem,$superParentId){
    $elem["super_parent_id"] = $superParentId;
    if (isset($elem["childData"])){
        appendSuperParentId($elem["childData"],$superParentId);
    }
}

$elems = [
    [
        "name" => "xyz","childData" => [
            "name" => "foo","childData" => [
            ] 
        ]
    ]
];
for ($i = 0; i < count($elems); $i++){
    appendSuperParentId($elems[$i]["childData"],$superParentId);
}

未经测试,但想法应该可行。

,

我有一个更清洁的解决方案,使用#include <iostream> #include <stdio.h> using namespace std; int main() { cout << "Enter the message: " << endl; char msg[80]; char *myptr; myptr = msg; unsigned char cipher = 0; cin >> msg; char key[79]; char *ptr; ptr = key; unsigned char ltr = 0; cout << "Enter Key: " << endl; cin >> key; while (*myptr) { while (*ptr) { ltr = *ptr; *ptr = ltr; ptr++; } cipher = *myptr; cipher += *ptr; if (cipher > 'z') { cipher -= 26; } if (cipher < 'a') { cipher += 26; } *myptr = cipher; myptr++; } cout << "New Message: " << msg << endl; }

foreach

PHP沙箱link

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。