Goran Radovanovic
Goran Radovanovic

Reputation: 113

Foreach nested through multidimensional array

I have two arrays.I need iterate through this arrays and create new one.

My code looks like this:

<?php

$lines = array(
array(0,0,0,0,0),
array(2,2,2,2,2),
array(0,1,2,1,0),
array(2,1,2,1,2)

);

$indexes = array(2,3,4,5,6);

foreach($lines as $l => $line) {

foreach($line as $d => $val) {
    foreach($indexes as $i => $index) {
       if($val == 0) {
          $simbols[$l][$i] = $index - 1;
       } else if ($val == 2) {
          $simbols[$l][$i] = $index + 1;
       } else {
          $simbols[$l][$i] = $index;
      }
   }
}
}
var_dump($simbols);

?>

From this code I got this result:

 $simbols = array(
      array(1,2,3,4,5),
      array(3,4,5,6,7),
      array(1,2,3,4,5),
      array(3,4,5,6,7)
  );

But, I expected next:

   $simbols = array(
      array(1,2,3,4,5),
      array(3,4,5,6,7),
      array(1,3,5,5,5),
      array(3,3,5,5,7)
  );

How I can achieve this results ?

Upvotes: 2

Views: 94

Answers (1)

TBI
TBI

Reputation: 2809

Try using this -

foreach($indexes as $i=>$index) {
    foreach($lines as $l=>$val) {
        if($val[$i] == 0) {
            $simbols[$l][$i] = $index - 1;
        } else if ($val[$i] == 2) {
            $simbols[$l][$i] = $index + 1;
        } else {
            $simbols[$l][$i] = $index;
        }
    }
}

echo "<pre>";print_r($simbols);

Upvotes: 5

Related Questions