0

So I have a variable which I explode:

$values = explode ('|', $split);

This can contain any number of values from 1 to 10+

I have another big array let's call it $tree. I need to loop round the $values whilst building up an array based on the $tree variable.

E.g:

$newArray = $tree [$values [0]][$values [1]];

But this needs to be done dynamically based on the number of elements in the $values array.

Any ideas?

3
  • 2
    And a foreach is not enough? Commented Dec 10, 2013 at 18:22
  • lol. many lookalike answers here. choose in all this. but I wonder, what is it exactly you want to do? any example of your arrays? give us a print_r or something like that :) Commented Dec 10, 2013 at 18:29
  • wait, you really mean that your keys in the $tree correspond to the values wxploded by split? do they always go by pairs, or sometimes you want the values associated to the first and third $value? Commented Dec 10, 2013 at 18:36

5 Answers 5

1

Is this what you're trying to do?

$newArray = array();
foreach($values as $key => $val)
{
    $newArray[] = $tree[$val][$values[$key + 1]];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need a foreach loop that goes to every single value you have and then put them in the $tree array something like:

$newArray = array();
foreach($values as $index => $value)
{
    $newArray[] = $tree[$value][$value[$index + 1]];
}

Comments

1

create a temporary array from $tree and iterate through the values getting each index:

$result = $tree;
foreach ($values as $val){
    $result = $result[$val];
}

This way you go down one level deeper into $tree with each value supplied in $values, and $result holds the value stored in $tree at the point you have reached. For example if you have a navigation tree, $values would be the "breadcrumb" of the current navigation position, and $result is the remaining tree from this point downwards.

Comments

0

I think this is what you want. It goes through pairs of elements of $values, using them as the indexes into $tree to add to $newArray

$newArray = array();
for ($i = 0; $i < count(values); $i += 2) {
    $newArray[] = $tree[$values[$i]][$values[$i+1]];
}

1 Comment

yeah, seems you got it right. or closest :) deletd mine since I was just going to duplicate yours.
0
$values=array(0, 1, 3);
$tree=array("First", "Second", "Third", "Fourth");
$newarray=array();

for ($i=0; $i<count($values); $i++)
{
    $newarray[]=$tree[$values[$i]];
}

echo(implode($newarray,", "));

Something like that what you were looking for?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.