麻烦在PHP中循环多维数组

时间:2012-06-27 13:48:54

标签: php arrays multidimensional-array

我有以下数组。它包含昵称和名称:

$nickAndNames = array( 
    array( "Johnie", "John Larson" ),
    array ("Maggie", "Margaret London" ),
    array("Nic","Nicholas Carradine")
);

你能帮我打印出第一个元素吗?我的意思是Johnie,Maggie,Nic。

6 个答案:

答案 0 :(得分:4)

数组的每个元素都是另一个数组。该内部数组的每个元素又包含2个元素:元素0(字符串,昵称)和元素1(另一个字符串,名称)。因此,您首先需要遍历$nicksAndNames数组,然后显示内部数组的第一个元素(即元素0):

// loop through $nickAndNames and assign, in turn, each inner array
// to a variable named $nickAndName
foreach ($nickAndNames as $nickAndName) {
    // this $nickAndName variable now contains the inner array, something like:
    // array("Johnie", "John Larson"), so "Johnie" is the first element,
    // element 0
    echo $nickAndName[0];
}

答案 1 :(得分:2)

您希望使用foreach循环遍历数组,然后打印第一个元素index 0

$nickAndNames = array( 
    array( "Johnie", "John Larson" ),
    array ("Maggie", "Margaret London" ),
    array("Nic","Nicholas Carradine")
);

foreach ($nickAndNames as $name) {
    echo $name[0];
}

答案 2 :(得分:1)

这将遍历所有名称:

foreach( $nickAndNames as $data)
    echo $data[0];

答案 3 :(得分:0)

看这里:

foreach ($nickAndNames as $key => $value) {
    var_dump($value[0]);
}

答案 4 :(得分:-2)

这应该给你一些工作:

foreach ($nickAndNames as $person)
{
    reset($person); // May not be needed.
    print current($person);
}

答案 5 :(得分:-2)

如果你可以使用如下所示的正确命名的键值对来纠正你的数组,

$nickAndNames = array( 
         array( "nickname" => "Johnie", "name" => "John Larson" ),
         array ("nickname" => "Maggie", "name" => "Margaret London" ),
         array("nickname" => "Nic","name" => "Nicholas Carradine")
         );

你可以做到

foreach($nickAndNames as $nickAndName){
    if(is_array($nickAndName))
    {
        foreach($nickAndName as $nN)
        {
             echo 'nickname = '. $nN['nickname'];
             echo 'name = '. $nN['name'];
        }
    }
    else
    {
        echo 'nickname = '. $nN['nickname'];
        echo 'name = '. $nN['name'];
    }
}

希望这有帮助,

KARTHIK