对如何遍历subArray感到困惑

时间:2018-08-12 20:31:37

标签: php arrays

首先,我在StackOverflow上搜索了类似的线程,例如this one

$myvar = array ("key_name" => array("tom", "an", "bob"),
     "key_age" => array("1", "10", "12")
    );

我尝试了很多事情,但我做不到

foreach($myvar as $i){
    foreach ($i as $key => $value) {
        echo print_r($i);
    }

2 个答案:

答案 0 :(得分:1)

  

我正在尝试获取“ key_name”并循环浏览

<?php
$myvar = array (
    "key_name" => array("tom", "an", "bob"),
    "key_age" => array("1", "10", "12")
);

foreach ($myvar['key_name'] as $value) {
    echo $value;
}

结果:

tomanbob

https://3v4l.org/tEFvS

如果您想遍历这两者:

foreach ($myvar as $sub_array) {
    foreach ($sub_array as $value) {
        echo $value;
    }
}

结果:

tomanbob11012

https://3v4l.org/cMFUh

签出http://php.net/manual/en/control-structures.foreach.php以获得使用foreach的信息

答案 1 :(得分:1)

您可以使用array_walker。因此,您可以执行以下操作:

array_walk($myvar,function($sub_items,$key){
echo "Key is >> " . $key . "\n";
foreach($sub_items as $item){
    echo $item . "\n";
}

echo "------------ \n ";

});

注意: 我在新行中添加了回声,以了解如何实现该功能!