我努力获得最高的id作为单独的记录,以防有一个子或更多的子json数组。
<?php
$data = json_decode('
[{"id":122943,
"children":[{"id":48614}]},
{"id":10009,
"children":[{"id":74311,
"children":[{"id":17988}]}]}]');
function parseJsonArray($jsonArray, $parentID = 0) {
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray->children)) {
$returnSubSubArray =
parseJsonArray($subArray->children, $subArray->id);
}
$return[] = array('id' => $subArray->id, 'parentID' => $parentID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
$readbleArray = parseJsonArray($data);
$i=0;
foreach($readbleArray as $row){
$i++;
echo("update cmm_master set parent = '".$row['parentID']."', sort = '".$i."' , master = '????' where PCR = '".$row['id']."' ")."<br>";
echo ("\r\n");
}
?>
通过上面的示例,我尝试获取每个项目的主记录,结果应为:
parent = '122943', sort = '1' , master = '122943' where PCR = '122943'
parent = '122943', sort = '2' , master = '122943' where PCR = '48614'
parent = '10009', sort = '3' , master = '10009' where PCR = '10009'
parent = '10009', sort = '4' , master = '10009' where PCR = '74311'
parent = '74311', sort = '5' , master = '10009' where PCR = '17988'
感谢您的帮助或信息
答案 0 :(得分:1)
尝试使用此代码:
<?php
$data = json_decode('
[
{"id":122943, "children":[
{"id":48614}
]
},
{"id":10009, "children":[
{"id":74311, "children":[
{"id":17988}
]}
]}
]
');
function parseJsonArray($jsonArray, $parentID = 0, $masterID = 0)
{
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray->children)) {
$returnSubSubArray =
parseJsonArray($subArray->children, $subArray->id, !$parentID ? $subArray->id : $masterID);
}
$return[] = array('id' => $subArray->id, 'parentID' => !$parentID ? $subArray->id : $parentID, 'masterID' => !$parentID ? $subArray->id : $masterID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
$readbleArray = parseJsonArray($data);
$i = 0;
foreach ($readbleArray as $row) {
$i++;
echo ("update cmm_master set parent = '" . $row['parentID'] . "', sort = '" . $i . "' , master = '".$row['masterID']."' where PCR = '" . $row['id'] . "' ");
echo("\r\n");
}
?>
它的输出如下:
update cmm_master set parent = '122943', sort = '1' , master = '122943' where PCR = '122943'
update cmm_master set parent = '122943', sort = '2' , master = '122943' where PCR = '48614'
update cmm_master set parent = '10009', sort = '3' , master = '10009' where PCR = '10009'
update cmm_master set parent = '10009', sort = '4' , master = '10009' where PCR = '74311'
update cmm_master set parent = '74311', sort = '5' , master = '10009' where PCR = '17988'