【发布时间】:2019-12-26 19:29:15
【问题描述】:
我一直坚持在第三个元素上分配 pid(父 ID)。我的意思是在setParent() 中,如果我在调用递归函数之前返回$array,那么我会看到“PC”和“Laptop”具有正确的 pid。
如果我运行所有脚本,那么我得到$newArr 是null。 PHP 7.3,Laravel 6。
我想做这个:
[
['pc', ['pc',null, null] ,'id'=>1,'pid'=>1],
['laptop', ['pc','laptop', null] ,'id'=>2,'pid'=>1],
['acc', ['pc','acc', null] ,'id'=>3,'pid'=>1],
['bags', ['pc','acc', 'bags'] ,'id'=>4,'pid'=>3],
['adapter', ['pc','acc', 'adapter'] ,'id'=>5,'pid'=>3],
['clothes', ['clothes',null,null] ,'id'=>6,'pid'=>6]
];
从那:
function test3(){
$array = [
['pc', ['pc',null, null] ,'id'=>1,'pid'=>0],
['laptop', ['pc','laptop', null] ,'id'=>2,'pid'=>0],
['acc', ['pc','acc', null] ,'id'=>3,'pid'=>0],
['bags', ['pc','acc', 'bags'] ,'id'=>4,'pid'=>0],
['adapter', ['pc','acc', 'adapter'] ,'id'=>5,'pid'=>0],
['clothes', ['clothes',null,null] ,'id'=>6,'pid'=>0]
];
$newArr = $this->setParent($array);
return response()->json([$newArr]);
}
function setParent($array, $goStop='go'){
if($goStop == 'go'){
$foundPids = 0;
foreach($array as $k => $v){
if( $v["pid"] == 0) $foundPids++;
}
if( $foundPids == 0){
return $this->setParent($array, 'stop'); // or return $array;
}
// parent search
foreach($array as $k1 => $v1){
if ($v1['pid']!=0)
break;
$keyInd = array_search($v1[0] , $v1[1]);// $v1 looks like {"0":"pc","1":["pc",null,null],"id":1,"pid":0}
if($keyInd == 0){
$array[$k1]['pid'] = $v1['id']; // PC updated
}
if($keyInd > 0){
$parentName = $v1[1][$keyInd-1];
$IdToWriteInPid = 0;
foreach ($array as $k1inner => $v1inner){
if($v1inner[$keyInd-1] == $parentName){
$IdToWriteInPid = $v1inner['id'];
}
}
$array[$k1]['pid'] = $IdToWriteInPid; // Laptop updated
//
// if uncomment, then i see that category PC having pid 1
// and category Laptop having pid 1. It is ok.
//
// return $array;
//
return $this->setParent($array, 'go' );
}
}
}
else return $array;
}
【问题讨论】:
-
条目可以在其后定义其父项吗?换句话说,那个起始(输入)数组可以是相反的顺序吗?
-
@Jeto 实际上没有。我需要导入 Excell,其中 3 列可以在内部数组中看到。