PHP数组没有正确迭代,只抓取第一个结果

时间:2013-08-05 04:38:34

标签: php arrays

这很有意思,让我难过。我有一个名为Workday的'order'对象数组,如果我print_r数组我得到以下内容;

Workday Object
(
    [workday] => Array
        (
            [0] => Order Object
                (
                    [id] => 3
                    [date] => 2013-08-02
                    [username] => userXYZ
                    [number] => 33333333 
                    [duration_start] => 20:51:00
                    [duration_end] => 21:51:00
                    [total] => $340.00
                )

            [1] => Order Object
                (
                    [id] => 3
                    [date] => 2013-08-03
                    [username] => userXXA
                    [number] => 87653212 
                    [duration_start] => 10:51:00
                    [duration_end] => 11:54:00
                    [total] => $20.00
                )

            [2] => Order Object
                (
                    [id] => 3
                    [date] => 2013-08-01
                    [username] => userXYD
                    [number] => 12345678 
                    [duration_start] => 08:37:00
                    [duration_end] => 10:01:00
                    [total] => $10.00
                )

        )

)

问题似乎是当我尝试迭代数组时它只输出第一个结果。我错过了什么?

$workday = new Workday();
$workday->Get($username, $duration_start, $duration_end);

$i = 0;
if($workday != null)
{
    foreach($workday as $orders)
    {
        echo "ID: " . $orders[$i]->number;
        $i++;
    }
}

3 个答案:

答案 0 :(得分:2)

试试这个

foreach($workday->workday as $orders)
    {
        echo "ID: " . $orders->number;
     }

答案 1 :(得分:0)

您需要遍历对象的workday成员变量

if($workday != null)
{
    foreach($workday['workday'] as $orders)
    {
        echo "ID: " . $orders->number;
    }
}

答案 2 :(得分:0)

你得到的错误是告诉你发生了什么:你正试图将一个对象用作数组。迭代$workday->workday代替(对象内部的数组)。

foreach ($workday->workday as $orders) { ... }