我想实现JSON格式
[{"name": "Niclas Superlongsurname",
"class": "male node-item",
"textClass": "emphasis",
"marriages": [{
"spouse": {
"name": "Iliana",
"class": "female"
},
"children": [{
"name": "James",
"class": "male",
"marriages": [{
"spouse": {
"name": "Alexandra",
"class": "female"
},
"children": [{
"name": "Eric",
"class": "male",
"marriages": [{
"spouse": {
"name": "Eva",
"class": "female"
}
}]
}, {
"name": "Jane",
"class": "female"
}, {
"name": "Jasper",
"class": "male"
}, {
"name": "Emma",
"class": "female"
}, {
"name": "Julia",
"class": "female"
}, {
"name": "Jessica",
"class": "female"
}]
}]
}]
}]
},{
"name": "Same level as Niclas",
"class": "male",
}]
数据库表,我有类似的东西
id | name | userID | relatedID | parentID | level
1 Jon 1 0 3 6
2 Jan 1 1 0 6
3 Mum 1 0 0 5
UserID用于区分用户和其他家庭 RelatedID用于配偶目的 ParentID用于父母。
我试图以递归方式实现此目的但仅在第一级失败。有人可以在递归部分帮助我吗?
$currentLvl = $result[0]["level"];
foreach($result as $id => $val)
{
// if(!in_array($val["relationshipID"], $doneArr))
//parent
if($val["parentID"] > 0)
{
$mainParentIndex = array_search($val["parentID"], array_column($relationshipArray, 'id')); // $key = 2;
$relationshipArray[$mainParentIndex]["marriages"][0]["children"][$childrenIndex]["name"] = $val["relationshipName"];
$relationshipArray[$mainParentIndex]["marriages"][0]["children"][$childrenIndex]["class"] = strtolower($val["relationshipGender"]);
$relationshipArray[$mainParentIndex]["marriages"][0]["children"][$childrenIndex]["id"] = strtolower($val["relationshipID"]);
$childrenIndex++;
//start
//end
}
else{
// {
if($val["relatedID"] == 0 && $val["parentID"] == 0)
{
$relationshipArray[$ownSiblingsIndex]["name"] = $val["relationshipName"];
$relationshipArray[$ownSiblingsIndex]["class"] = strtolower($val["relationshipGender"]);
$relationshipArray[$ownSiblingsIndex]["id"] = $val["relationshipID"];
$doneArr[] = $val["relationshipID"];
$ownSiblingsIndex++;
}
//is a spouse
if($val["relatedID"] > 0)
{
$mainSpouseIndex = array_search($val["relatedID"], array_column($relationshipArray, 'id')); // $key = 2;
//echo $val["relationshipID"]."-".$val["relatedID"]."- ".$mainSpouseIndex."<br>";
$relationshipArray[$mainSpouseIndex]["marriages"][0]["spouse"]["name"] = $val["relationshipName"];
$relationshipArray[$mainSpouseIndex]["marriages"][0]["spouse"]["class"] = strtolower($val["relationshipGender"]);
$relationshipArray[$mainSpouseIndex]["marriages"][0]["spouse"]["id"] = $val["relationshipID"];
$doneArr[] = $val["relationshipID"];
$removeArr[] = $val["relationshipID"];
}
}