问题描述
我有一个以下格式的数组。 示例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