如何在PHP中使用数组?

时间:2011-05-26 13:38:59

标签: php

当我print_r($ a);像这样的输出:

Array
(
    [0] => stdClass Object
        (
            [tid] => 3
            [vid] => 1
            [name] => cPanel
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [1] => stdClass Object
        (
            [tid] => 4
            [vid] => 1
            [name] => whm
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [2] => stdClass Object
        (
            [tid] => 5
            [vid] => 1
            [name] => test
            [description] => 
            [format] => 
            [weight] => 0
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

)

数组键可能会递增。现在,我想输出数组的所有name' s值。 当我使用以下代码。它显示了一个错误。

foreach($a as $a->name){
    echo a->name;
}

6 个答案:

答案 0 :(得分:3)

试试这个:

foreach($a as $value){
   echo $value->name;
}

答案 1 :(得分:2)

使用 - >用于物体; =>用于数组


foreach($a as $key => $value){
    echo $key . " " . $value;
}

答案 2 :(得分:2)

这样做:

foreach($a as $object){
    echo $object->name;
}

然后阅读:http://php.net/manual/en/control-structures.foreach.php

这样做的:

foreach ($array as $key => $value) {
    echo "Array key: $key   Value: $value";
}

将打印出数组中的每个值和密钥的名称。

答案 3 :(得分:1)

数组包含许多对象,但foreach循环的工作方式与普通变量完全相同。正确的语法是

foreach ($a as $object)
 echo $object->name;

答案 4 :(得分:0)

典型的foreach语法使用key => value对。

foreach ($a as $key => $value)
{
 var_dump($value);
}

答案 5 :(得分:0)

这就是答案:

foreach($a as $value)
echo $value['name'];