我如何为每个循环打印数组

时间:2014-12-10 07:20:25

标签: php arrays

<?php

    $students = array(      
        "student1" => array(
            "age" => 36,
            "gender" => "male",
            "qualification" => "Master",
        ),
        "student2" => array(
            "age" => 25,
            "gender" => "male",
            "qualification" => "BA",
        ),
        "student3" => array(
            "age" => 26,
            "gender" => "male",
            "qualification" => "BA",
        ),
        "student4" => array(
            "age" => 25,
            "gender" => "male",
            "qualification" => "BA",
        ),
        "student5" => array(
            "age" => 20,
            "gender" => "male",
            "qualification" => "Master",
        ),
        "student6" => array(
            "age" => 20,
            "gender" => "male",
            "qualification" => "F.A",
        ),
    );

    ?>  

我需要这样的结果。

Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master.

Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA.

我试过这样的。

foreach($students as $key=>$value)
{
    echo "Mr".$key."<br />";
        foreach($value as $key=>$value)
    {
        echo" Your  $key  is  $value  and <br />";

    }
}

我的结果是这样的。

Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master and

Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA and

3 个答案:

答案 0 :(得分:1)

不需要其他foreach,你可以只使用一个。子数组的每个副本($info),您只需调用其索引。

foreach ($students as $name => $info) {
    echo "
    Hello $name, <br/>
    Your age is: $info[age] <br/>
    Your gender is: $info[gender] <br/>
    Your qualification is: $info[qualification] <hr/> 
    ";
}

但是如果你真的想要去两条foreach路线,是的,你可以在第二个循环中添加一个条件,以防止它添加多余的and

foreach ($students as $name => $info) {
    echo "Hello $name ";
    foreach($info as $att => $val) {
        echo "Your $att is: $val ", (end($info) != $val) ? ' and ' : '<br/>';
    }
}

答案 1 :(得分:0)

尝试 -

foreach($students as $key=>$value)
{
    echo "Mr".$key."";
    $count = 1;
    foreach($value as $key=>$val)
    {
        echo" Your  $key  is  $val";
        if ($count != count($val)) {
            echo " and ";
        }

    }
}

答案 2 :(得分:0)

试试这段代码:

foreach($students as $key => $value) {
   echo 'Hello ', $key, '  Your age is ', $value['age'], ' gender is ' . $value['gender'], ' and Your qualification is ', $value['qualification']
}

您可以使用echo连接字符串,但昏迷会更好地提高性能。