skip to Main Content

So I have two-dimensional arrays of N * M like below,

$arys = [
    [0] => [0, 0 , 0 , 0],
    [1] => [0, 1 , 0 , 0],
    [2] => [0, 0 , 1 , 0],
    [3] => [0, 0 , 0 , 0],

and need to detect ‘1’ and if there’s ‘1’, i need to get values vertically and horizontally, and change them to ‘1’, which is like below,

$arys = [
    [0] => [0, 1 , 1 , 0],
    [1] => [1, 1 , 1 , 1],
    [2] => [1, 1 , 1,  1],
    [3] => [0, 1 , 1 , 0],

I kind found out that I need to use ‘for’ inside ‘for’, but can’t do that.
Guess this is a very basic PHP code but appreciate if someone would help with it.

2

Answers


  1. The basics of it is:

    for( $y=0, $n=count($ary); $y < $n; ++$y ) {
      for( $x=0, $m=count($ary[$y]); $x < $m; ++$x ) {
        $current_cell = $ary[$y][$x];
        // relevant code here.
      }
    }
    

    But the pitfall you’re going to run into is if you start changing zeroes to ones in the array you’re currently reading you’re going to wind with incorrect output. Write your output to a new 2D array.

    Login or Signup to reply.
  2. 2 foreach loops are used to iterate over all elements of $arr. If there is a 1 in the row or in the column (via array_column), the new value is also set to 1, otherwise 0.

    $arr = [
        0 => [0, 0 , 0 , 0],
        1 => [0, 1 , 0 , 0],
        2 => [0, 0 , 1 , 0],
        3 => [0, 0 , 0 , 0],
    ];
    
    $new = [];
    foreach($arr as $r => $row){
      foreach($row as $c => $val){
        $new[$r][$c] = (in_array(1,$row) OR in_array(1,array_column($arr,$c))) ? 1 : 0;
      }
    }
    
    var_dump($new);
    

    Demo : https://3v4l.org/XYS0a

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search