zhuanzhou
zhuanzhou

Reputation: 2453

Get values from a column in an array of objects

When I print_r($a); the output like this:

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
                )

        )

)

the array key maybe increment. now, i want to output all the name' s value of the array. when i used the following code. it shows me an error.

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

Upvotes: 0

Views: 225

Answers (6)

Sujit Agarwal
Sujit Agarwal

Reputation: 12518

This is the answer:

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

Upvotes: 0

user542603
user542603

Reputation:

Do this:

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

Then read this: http://php.net/manual/en/control-structures.foreach.php

Doing:

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

Will print out each value in an array and the name of the key.

Upvotes: 2

Dave Kiss
Dave Kiss

Reputation: 10495

The typical foreach syntax used a key => value pair.

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

Upvotes: 0

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

Try this:

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

Upvotes: 3

Pekka
Pekka

Reputation: 449783

The array contains a number of objects, but the foreach loop will work exactly the same way as for normal variables. The correct syntax is

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

Upvotes: 1

AllisonC
AllisonC

Reputation: 3100

Using -> is for objects; => is for arrays


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

Upvotes: 2

Related Questions