Frage

I'm trying to use a recursive function to build an array with inheritance.

Let's say I have an object "a" that looks like this (with a Parent ID of "b")

a = 'Item 1', 'Item 2', Parent_ID, 'Item 3', 'Item 4'

And I have an object "b" that looks like this:

b = 'Item X', 'Item Y'

And the desired result is this:

final = 'Item 1', 'Item 2', 'Item X', 'Item Y', 'Item 3', 'Item 4'

So basically array_splice function that continues to look for a parent ID and inserts the parent items. I'm going this direction on the code:

$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);
}

My function is returning this as the (undesired) result:

final = 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item X', 'Item Y'

Obviously this is pseudo-code and is only intended to get the point across. Can anyone point me in the right direction? I greatly appreciate it.

War es hilfreich?

Lösung 2

Ahh!, I was able to figure it out:

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
}

I appreciate everyone's help.

Andere Tipps

I would say something like use array_walk() to parse the array

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);

note: if you wanted to do something like this but instead based on key and not value you could just use array_replace().

not the most graceful but here.

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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top