简体   繁体   中英

Printing nested array values

we are doing the following programming exercise: Average Array .

We first tried to output the nested array values to the console as follows:

function avgArray($arr) {

  print_r($arr);
  print_r($arr[0]);
  echo $arr[0][0];
  var_dump($arr[0]);
  foreach($arr as $var){
    echo "\n",$var;
  }
  foreach($arr as $outers){
    foreach($outers as $inners){
      echo $inners;
    }
  }
  foreach($arr as $key => $value){
    echo $value;
  }
  for($i=0;$i<sizeof($arr,0);$i++){
    for($j=0;$j<sizeof($arr,1);$j++){
      echo $arr[$i][$j];
    }
  }


  return $arr;
}

However nothing shows in the console.

The tests are as follows:

class SolutionTest extends TestCase {
  public function testFixedTests() {
    $this->assertEquals([3, 4, 5, 6], avgArray([[1, 2, 3, 4], [5, 6, 7, 8]]));
    $this->assertEquals([22.5, 11, 38.75, 38.25, 19.5], avgArray([[2, 3, 9, 10, 7], [12, 6, 89, 45, 3], [9, 12, 56, 10, 34], [67, 23, 1, 88, 34]]));
    $this->assertEquals([0, 0, 1, 5, -4.5], avgArray([[2, 5, -4, 3, -19], [-2, -5, 6, 7, 10]]));
    $this->assertEquals([-1, -31.5, -32.5, -22], avgArray([[-2, -18, -45, -10], [0, -45, -20, -34]]));
    $this->assertEquals([1.6, 6.5105, 2.075, 2.0635, 1.45], avgArray([[1.2, 8.521, 0.4, 3.14, 1.9], [2, 4.5, 3.75, 0.987, 1.0]]));
  }
}

So, when we execute the tests, we see the following output:

在此处输入图像描述

We would like what is inside each nested array.

Then, we tried to solve the exercise as follows:

function avgArray($arr) {


  for($i=0;$i<count($arr[0]);$i++){
    for($j=0;$j<count($arr);$j++){
      $result[$i][$j]=$arr[$j][$i];
      echo $result[$i][$j];
    }
    $result[$i]=array_sum($result[$i])/count($arr);
  }

  return $result;

}

However we do not see the echo being printed to the console.

We wonder how could we print $arr for debugging purposes?

We have read:

Try to traverse array in a recursive way.

function searchFun($sourceArray)
{
    if(is_array($sourceArray) && count($sourceArray)>0)
    {
        foreach($sourceArray as $key=>$value) {
             if(is_array($value) && count($value) > 0) { 
                $res_path = searchFun($value ); 
            }
            else { 
                echo $key .' : '. $value;
            }           
        }

    }
}

$x = []; //set your nested array here;

searchFun($x);

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