D
D
Dealaxer2016-08-21 17:15:01
PHP
Dealaxer, 2016-08-21 17:15:01

PHP How to run two JSON arrays through one Foreach?

Welcome all!
There are two different arrays that do not resemble each other in any way. I run them through foreach:

foreach($arr['value'] as $key=>$val){
//Выполнение начального кода

                foreach($arr2['value'] as $key=>$val2){
                //выполнение кода во втором цикле
                }
//Выполнение последующего кода
}

I can’t figure out how to make the cycles work alternately, that is:
In the 1st pass / iteration of the 1st cycle, the child / second cycle also made the 1st pass, paused and after the 1st cycle starts to make the 2nd pass, the child cycle also started the 2nd pass from the place where it stopped and so on until 1 cycle has made all the passes.
Has anyone done this?
Please advise how to do this.
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
romy4, 2016-08-21
@Dealaxer

There are several options.
1. pull out all the keys from the first and from the second into arrays. and then banal enumeration

$keys1 = подставьте тут сами;)
$keys2 = и тут ;)
for ( $k=0; $k < count($keys1) && $k < count($keys2); $k++)
{
   $value_from_arr1 = $arr['value'][$keys1[$k]];
   $value_from_arr2 = $arr2['value'][$keys2[$k]];
   // do stuff
}

for example here
and still there is a piece "generators". in the end you get the same thing, but syntactically prettier.
function from_arr(&$arr)
{
 //
}

while ( ($value1 = from_arr($arr1))!==null && ($value2 = from_arr($arr2))!==null)
{
   // do_stuff
}

something like that. You can make it more complicated, but it's not necessary.

L
Lander, 2016-08-21
@usdglander

Nested loops will not work for you here. Use while on indexes or something like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question