简体   繁体   中英

PHP change multidimensional array index in running foreach

I am trying to change multidimensional array index in running foreach:

$array = array(
    array("apple", "orange"),
    array("carrot", "potato")
    );

$counter = 0;

foreach($array[$counter] as &$item) {
    echo $item . " - ";
    $counter = 1;
}

I supposed, that output would be apple - carrot - potato - , because in first run it takes value from zero array and then in next runs values from first array.

However, the output is apple - orange -

I tried add "&" before variable $item, but i guess it is not what I am looking for.

Is there any way to do it?
Thank you

// Well, i will try to make it cleaner:
This foreach takes values from $array[0], but in run i want to change index to 1, so in next repeat it will take values from $array[1]

Is that clear enough?

Note: I do not know how many dimensions my array has.

My purpose of this is not to solve this exact case, all I need to know is if is it possible to change source of foreach loop in run:

My foreach

$counter = 0;
foreach($array[$counter] as $item) {
 echo $item . " - ";
}

is getting values from $array[0] right now. But inside it, I want to change $counter to 1, so next time it repeats, it will get values from $array[1]

$counter = 0;
foreach($array[$counter] as $item) {
 echo $item . " - ";
 $counter = 1;
}

I see, it is kind of hard to explain. This is how foreach should work:
Index of $array is $counter

First run
$array[0] -> as $item = apple
echo apple
wait, now counter changes to 1

Second run
$array[1] -> as $item = carrot
echo carrot

Third run
$array[1] -> as $item = potato
echo potato

END

I am really trying to make it clear as much as possible :D

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. Now, by changing counter, you are changing the array (the inside one), but it is set to the first array again.

Changing the array in between may result in unexpected behaviour.

Source: Foreach: PHP.net

So finally, I found a time for this, and this is how you can change index of source array in running loop.

Thanks to you, I realized, that i can not do this by foreach, but there are many other loops.

If you were facing the same problem, here is my solution:

$array = array(
 array("apple", "orange"),
 array("carrot", "potato")
);

$counter = 0;
$x = 0;

while($x < count($array[$counter])) {
    echo $array[$counter][$x] . " - ";
    $x++;
    if($counter == 0) {
        $x = 0;
        $counter = 1;
    }
}

And the output is: apple - carrot - potato - as I wanted to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM