Php 构建数组的递归函数
我正在尝试使用递归函数来构建具有继承性的数组 假设我有一个像这样的对象“a”(父ID为“b”) 我有一个对象“b”,看起来像这样:Php 构建数组的递归函数,php,arrays,recursion,array-splice,Php,Arrays,Recursion,Array Splice,我正在尝试使用递归函数来构建具有继承性的数组 假设我有一个像这样的对象“a”(父ID为“b”) 我有一个对象“b”,看起来像这样: b = 'Item X', 'Item Y' 期望的结果是: final = 'Item 1', 'Item 2', 'Item X', 'Item Y', 'Item 3', 'Item 4' 所以基本上是数组拼接函数,它继续查找父ID并插入父项。我将沿着代码的这个方向: $master_list = array(); getItems("a", $mast
b = 'Item X', 'Item Y'
期望的结果是:
final = 'Item 1', 'Item 2', 'Item X', 'Item Y', 'Item 3', 'Item 4'
所以基本上是数组拼接函数,它继续查找父ID并插入父项。我将沿着代码的这个方向:
$master_list = array();
getItems("a", $master_list);
function getItems($ID, &$master_list){
$master_list = retrieve_items($ID); // returns items from "a"
//if Parent ID exists, run function again to retrieve items from parent and insert them in place of the Parent ID
if(Parent_ID)
array_splice($master_list, [parent index], 1, getItems($parentID, $master_list);
}
我的函数将此作为(不希望的)结果返回:
显然,这是伪代码,仅用于获取点。谁能给我指出正确的方向吗?非常感谢。我想说一些类似于使用array\u walk()来解析数组的东西
function insert_array(&$item1, $key, $userdata) {
if($item1 === $userdata['Product_ID']) {
$item1 = $userdata['insert'];
}
}
$data['product_id'] = PRODUCT_ID;
$data['insert'] = $b;
array_walk($a,'insert_array',$data);
注意:如果您想执行类似的操作,但基于键而不是值,则可以使用array_replace()
这里不是最优雅的
while(in_array(Parent_ID,$a,false)) {
foreach($a as $value) {
if($value != Parent_ID) {
$temp[] = $value;
} else {
foreach($b as $key => $value2) {
$temp[] = $value2;
}
}
}
$a = $temp;
unset($temp);
}
啊!,我终于想出来了:
master_list = buildList(list_id)
function buildList(list_id){
list = getItems(list_id) //example 'A', 'B', parent_id, 'C'
if(parent_id){
array_splice( list, index_of_parent_id, 1, buildList(parent_id) )
}
return list
}
我感谢大家的帮助。谢谢你的建议。不过,我不确定它是否适用于多个级别。例如,如果$b中的元素还包含一个父ID。很抱歉,我应该更具体地说明要求。无论如何,这不会起作用,这段代码会将一个数组放在Product_ID的位置,而不是在数组中切片
while(in_array(Parent_ID,$a,false)) {
foreach($a as $value) {
if($value != Parent_ID) {
$temp[] = $value;
} else {
foreach($b as $key => $value2) {
$temp[] = $value2;
}
}
}
$a = $temp;
unset($temp);
}
master_list = buildList(list_id)
function buildList(list_id){
list = getItems(list_id) //example 'A', 'B', parent_id, 'C'
if(parent_id){
array_splice( list, index_of_parent_id, 1, buildList(parent_id) )
}
return list
}