大家好日子。我试图模拟(使用php),json的类似xml的结构 如下:
{
"Articles": [
{
"Article": {
"ID": 111,
"title": Origin of man",
"author": "Man and Woman",
"pubDate": "21st Feb, 2014",
"summary": "Both Idiots"
}
},
{
"Article": {
"ID": 222,
"title": "Origin of Animals",
"author": "Animal and Man",
"pubDate": "22nd Feb, 2014",
"summary": "Yet another Idiots"
}
},
{
"Article": {
"ID": 333,
"title": "Origin of Politicians",
"author": "Politicians and Man",
"pubDate": "23rd Feb, 2014",
"summary": "Inexplicable Idiots"
}
}
]
}

{
"Articles": [
{
"Article": {
"ID": 111,
"title": Origin of man",
"author": "Man and Woman",
"pubDate": "21st Feb, 2014",
"summary": "Both Idiot"
}
},
{
"Article": {
"ID": 222,
"title": "Origin of Animals":
"SUB-TITLES":
{
"SUB_TITLE_1": "Just kidding",
"SUB_TITLE_2": "Still Kiddng",
"SUB_TITLE_3": "Dont be offended"
}
"author": "Animal and Man",
"pubDate": "22nd Feb, 2014",
"summary": "Yet another Idiots"
}
},
{
"Article": {
"ID": 333,
"title": "Origin of Politicians",
"author": "Politicians and Man",
"pubDate": "23rd Feb, 2014",
"summary": "Inexplicable Idiots"
}
}
]
}

这是我的尝试,但看起来不够好 虽然一切顺利但没有错误, 但输出并不是我实际期待的。在这里:
{
"Articles": [
{
"Article": {
"ID":111,
"title":"Origin of man",
"author":"Man and Woman",
"pubDate":"21st Feb, 2014",
"summary":"Both Idiot"
}
},
{
"Article": {
"ID":222,
"title":"Origin of Animals":
//i expected to have SUB-TITLES record here, but didnt
"author":"Osagie Odigie",
"pubDate":"22nd Feb, 2014",
"summary":"Yet another Idiots"
}
},
{
"Article": {
"ID":333,
"title": "Origin of Politicians",
"author": "Politicians and Man",
"pubDate": "23rd Feb, 2014",
"summary": "Inexplicable Idiots"
}
}
],
//Now, here's where SUB-TITLES record showed up
"0":{ "SUB-TITLES": [
{"SUB_TITLE_1": "Just kidding"},
{"SUB_TITLE_2": "Still Kiddng"},
{"SUB_TITLE_3": "Dont be offended"}
]
}
}

Sure ! i anticipate writing it to my file for permanent
storage if all goes fine. for now, i'm just displaying it on my browser
using:
echo json_encode($data);
Here's an extract of the code:
function JSONAddRecordToChild(array $Record, $ChildID){
$file = file_get_contents("File.json", true);
$data = json_decode($file, true); //get json by assoc array
unset($file); //prevent memory leaks for large json
//only when ID does not exist, write record to json
$node = $this->searchJSON($data["Articles"], $ChildID); //costumized searchJSON methode that returns a matching node
if($node != null){
$node = array("SUB-TITLES" => array());
foreach ($Record as $key => $value){
$node["SUB-TITLES"][] = array($key => $value);
}
foreach ($data as $child){
foreach ($child as $son){
if($son["Article"]['ID'] == $ChildID){
$data[] = $node;
}
}
}
echo json_encode($data).;
//to be written permanently to file as mentioned
}
}

答案 0 :(得分:0)
看起来问题出在你上一个foreach
循环中。您正在检查内部元素$son
是否与所需的ID匹配,但是您要在根级$data
上设置子标题
TL; DR Change
if($son["Article"]['ID'] == $ChildID){
$data[] = $node;
}
到
if($son["Article"]['ID'] == $ChildID){
$son["Article"][] = $node;
}