循环数组包含3个类

时间:2010-12-09 14:01:13

标签: php arrays loops

我无法理解如何遍历stdClasses。

打印阵列给出了以下内容:

Array
(
    [piggyback] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1003
                    [entity_id] => 0
                    [redirect_url] => http://yahoo.com
                    [type] => Image
                )

        )

    [total_count] => 1
)
Array
(
    [piggyback] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1002
                    [entity_id] => 0
                    [redirect_url] => http://google.com
                    [type] => Image
                )

        )

    [total_count] => 1
)
Array
(
    [piggyback] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1001
                    [entity_id] => 0
                    [redirect_url] => http://bing.com
                    [type] => Image
                )

        )

    [total_count] => 1

我试图循环使用以下内容并打印出一个值(id),但我一无所获。

foreach ($piggies_array as $key => $value) {
  echo $piggies_array[$key]['id'];
}

3 个答案:

答案 0 :(得分:3)

foreach ($piggies_array as $key => $value) {
if (is_array($value)){
  echo $value[0]->id;
 }
}

答案 1 :(得分:1)

我认为你需要:

for ($i = 0; $i < count($piggies_array); $i++) {
    echo $piggies_array[$i]['piggyback'][0]->id;
}

...假设我们只能看到你输出的一部分;)

答案 2 :(得分:0)

尝试将其替换为echo $value->id;