我在一个名为family 的数组中创建了一个数组mike 和john。如何使用 foreach 循环打印数组 mike 和 john 的值
<?php
$families = array(
$Mike = array("Mike","abc", "def"),
$john = array("John","efg", "ghi", "xyz")
);
?>
您应该尝试一下,但这里有一个帮手:
$families = array(
'mike' => array(
'name'=>'Mike',
'value1'=>'abc',
'value2'=>'def'
)
);
foreach ($families as $family) {
echo $family['name'];
}
首先,让你的数组正确:
<?php
$families = array(
'Mike' => array("Mike","abc", "def"),
'john' => array("John","efg", "ghi", "xyz")
);
?>
如果$Mike
并且$john
包含您想要作为键的值,请改为执行以下操作:
<?php
$families = array();
$families[$Mike] = array("Mike","abc", "def");
$families[$john] = array("John","efg", "ghi", "xyz");
?>
现在,您可以遍历数组:
<?php
foreach ($families as $key => $val) {
echo "$key = ";
print_r($val);
}
?>
$key 将是数字索引或显式键值。
你可以试试这样
<?php
$rockBands = array(
array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
array('Rolling Stones','Waiting on a Friend','Angie','Yesterday\'s Papers'),
array('Eagles','Life in the Fast Lane','Hotel California','Best of My Love')
);
?>
<table border="1">
<tr>
<th>rockBand</th>
<th>Song 1</th>
<th>Song 2</th>
<th>Song 3</th>
</tr>
<?php
foreach($rockBands as $rockBand)
{
echo '<tr>';
foreach($rockBand as $item)
{
echo "<td>$item</td>";
?>
它在我身边工作正常......它可以帮助你