使用For Each Loop的Echo多维数组

时间:2013-09-10 19:11:47

标签: php arrays foreach

我在一个名为families的数组中创建了一个数组mike和john。如何使用foreach循环打印数组mike和john的值

   <?php
    $families = array(
        $Mike = array("Mike","abc", "def"),
        $john = array("John","efg", "ghi", "xyz")
    );
   ?>

3 个答案:

答案 0 :(得分:2)

你应该尝试,但这是一个帮手:

$families = array(
    'mike' => array(
        'name'=>'Mike', 
        'value1'=>'abc', 
        'value2'=>'def'
        )
);

foreach ($families as $family) {
    echo $family['name'];
}

答案 1 :(得分:0)

首先,让你的阵列正确:

<?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将是数字索引或显式键值。

答案 2 :(得分:0)

你可以这样尝试

<?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>";



?>

它在我身边工作得很好......可能对你有所帮助