0

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

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

你能帮我打印第一个元素吗?我的意思是约翰尼、玛吉、尼克。

4

6 回答 6

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];
}
于 2012-06-27T13:50:51.857 回答
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];
}
于 2012-06-27T13:51:33.377 回答
1

这将遍历所有名称:

foreach( $nickAndNames as $data)
    echo $data[0];
于 2012-06-27T13:51:01.367 回答
0

看这里:

foreach ($nickAndNames as $key => $value) {
    var_dump($value[0]);
}
于 2012-06-27T13:51:00.363 回答
-2

这应该给你一些工作:

foreach ($nickAndNames as $person)
{
    reset($person); // May not be needed.
    print current($person);
}
于 2012-06-27T13:51:10.977 回答
-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'];
    }
}

希望这可以帮助,

卡尔提克

于 2012-06-27T13:53:57.657 回答