简体   繁体   English

如何循环遍历这个数组?

[英]How to loop through this array?

I have this array where the first two elements are integers and the third element is another array containing 2 arrays, each with one element.我有这个数组,其中前两个元素是整数,第三个元素是另一个包含 2 个 arrays 的数组,每个元素都有一个元素。 I can loop through the first 2 elements fine but not the third element.我可以很好地循环前两个元素,但不能循环第三个元素。

I have tried using a second foreach loop and also a for loop containing a foreach loop.我尝试过使用第二个 foreach 循环和一个包含 foreach 循环的 for 循环。

$rows  =  array(1, 2, "qa" => array("q" => array(1,2), "b" => array(3,4)));
$f=1;

foreach($rows as $r) {
   if($f == 1){
      $e = $rows[0];
      $f=$f+1;
   }
   if($f == 2){
      $u = $rows[1];
   }
   if($r == "qa"){
      $c = $value["q"];
      $d = $value["b"];

   }    
} 

echo $e;
echo $u;
print_r($c);
print_r($d);

I hope this helps:我希望这有帮助:

$rows  =  array(1, 2, "qa" => array("q" => array(1,2), "b" => array(3,4)));
view($rows);
function view($arr) {
    foreach ($arr as $value) {
        if (is_array($value))
            view($value);
        else
            echo $value;
    }
}

You could use array_walk_recursive你可以使用array_walk_recursive

array_walk_recursive($rows, function($v){echo $v;});

DEMO: https://3v4l.org/ITXAu演示: https://3v4l.org/ITXAu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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