【发布时间】:2017-01-10 03:14:21
【问题描述】:
我只想从每个数组中输出名字。 下面代码中的我的 cmets 进行了解释。我不想要钥匙, 只是价值。从我下面的描述中你会看到, 我很想有一个能产生预期结果的循环。 是否有一个只会返回“firstName”值的循环? 谢谢....
<?php
$contacts = array(
array(
'firstName' => "Hoth",
'lastName' => "Omiaenoed",
'address'=> "76 S. Mammoth St.",
'city' => "Westfield",
'state' => "MA",
'zip' => "01085",
),
array(
'firstName' => "Akae",
'lastName' => "Uniaebul",
'address'=> "8038 Shadow Brook Street",
'city' => "Ocoee",
'state' => "FL",
'zip' => "34761",
),
array(
'firstName' => "Upae",
'lastName' => "Aesuudoes",
'address'=> "7044 N. School St.",
'city' => "Riverdale",
'state' => "GA",
'zip' => "30274",
),
array(
'firstName' => "Doer",
'lastName' => "Waezoeyo",
'address'=> "338 Old Griffin St.",
'city' => "Antioch",
'state' => "TN",
'zip' => "37013",
),
array(
'firstName' => "Ozae",
'lastName' => "Iraeoewif",
'address'=> "65 West Chapel Dr.",
'city' => "San Angelo",
'state' => "TX",
'zip' => "76901",
),
array(
'firstName' => "Naes",
'lastName' => "Ebaeaeraesh",
'address'=> "34 Tower Street",
'city' => "Huntersville",
'state' => "NC",
'zip' => "28078",
)
);
/* I want to echo (print) just the first names from each array. I hoped I could use a "foreach" loop to do this and it seemed to me the one just below should work */
foreach ($contacts['firstName'] as $fname) {
while (list( , $firstn) = each($fname)) {
echo "$firstn <br/>";
}
echo "------------------------------------------<br/>";
}
/* But it does not. Adding in ['firstName'] does not work. So, I have to use this one below, for lack of knowing what else to do. */
echo $contacts[0]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
echo $contacts[1]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
echo $contacts[2]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
echo $contacts[3]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
echo $contacts[4]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
echo $contacts[5]['firstName']; echo "<br/>";
echo "------------------------------------------<br/>";
/* I used this to output each complete array and it works just fine. */
foreach ($contacts as $info) {
while (list( , $lines) = each ($info)) {
echo "$lines <br/>";
}
echo "<hr/>";
}
?>
【问题讨论】:
-
它的
foreach ($contacts as $values) { echo $values['firstName'] }不是$contacts['firstName'],可以这样想:$contacts内部的每个子数组都是$values,firstName在$values内部 -
非常感谢!我使用它对外观进行了轻微修改。 foreach ($contacts as $fnv) { echo $fnv['firstName'] ;回声“
”;回声“------------------------------
”; } 回声“
”;
标签: php loops multidimensional-array echo associative-array