Hi guys I was wondering how can I add a parent ID in the children?
嗨,伙計們,我想知道如何在孩子們中添加家長ID ?
Ex: MY_ARRAY
例:MY_ARRAY
(
[id] => 4
[children] => Array
(
[0] => Array
(
[id] => 18
[children] => Array
(
[0] => Array
(
[id] => 21
)
[1] => Array
(
[id] => 22
)
)
)
[1] => Array
(
[id] => 19
)
[2] => Array
(
[id] => 20
[children] => Array
(
[0] => Array
(
[id] => 26
)
)
)
)
)
And as of now these are the codes that I did but still not giving me the correct result.
到現在為止,這些是我做過的代碼但仍然沒有給出正確的結果。
$in = MY_ARRAY
function generateArray($in, $out, $parent = 0, $prev_par = 0){
foreach($in as $key => $value) {
$childs = false;
if(isset($value['children'])){ // if there is children
$childs = $value['children'];
unset($value['children']);
}
if($prev_par != $parent){
$prev_par = $parent;
}
else{
$prev_par = $prev_par;
}
$out[] = array($value['id'],$parent,$prev_par);
if($childs){
$parent = $value['id'];
$out = $this->generateArray($childs, $out, $parent, $prev_par);
}
}
return $out;
}
I would need to add an Parent ID becaue as of now it I can retrive their heirarchy without displaying correnct Parent ID.
我需要添加父ID,因為到目前為止,我可以在不顯示correnct父ID的情況下檢索它們的繼承關系。
The output could look like this. As long as I can add the Parent ID.
輸出可能是這樣的。只要我可以添加父ID。
[id] => 4
[P_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 18
[P_id] => 4
[children] => Array
(
[0] => Array
(
[id] => 21
[P_id] => 18
)
[1] => Array
(
[id] => 22
[P_id] => 18
)
)
)
[1] => Array
(
[id] => 19
[P_id] => 4
)
[2] => Array
(
[id] => 20
[P_id] => 4
[children] => Array
(
[0] => Array
(
[id] => 26
[P_id] => 20
)
)
)
)
)
Need really help here thanks guys...
這里真的需要幫助,謝謝大家……
1 个解决方案
#1
4
Your problem is solved, check it. The function is recursively push p_id and another point is if the array contain numeric index then it will skip to push p_id.
你的問題解決了,檢查一下。函數遞歸地推p_id,另一點是如果數組包含數值索引,那么它將跳過來推p_id。
Function is:
函數是:
function generateArray($in, $parent = 0){
foreach ($in as $key => $value) {
if(is_numeric($key)){
$in = $value;
$out[$key] = generateArray($in, $parent);
}else{
$out[$key]=$value;
if($key=="id"){
$out['p_id']=$parent;
$parent=$value;
}elseif($key=="children"){
$in = $value;
$out[$key] = generateArray($in, $parent);
}
}
}
return $out;
}
Working example:
工作的例子:
$my_array =array(
'id'=> 4,
'children'=> Array(
'0'=> Array(
'id'=> 18,
'children'=> Array(
'0'=> Array(
'id'=> 21,
),
'1'=> Array(
'id'=> 22,
),
),
),
'1'=> Array(
'id'=> 19,
),
'2'=> Array(
'id'=> 20,
'children'=> Array(
'0'=> Array(
'id'=> 26,
),
),
),
)
);
$newarray = generateArray($my_array);
print_r($newarray);