访问数组值时非法字符串偏移量

时间:2018-01-23 11:15:34

标签: php arrays

我有以下名为$shops的数组:

Array
(
    [0] => Array
        (
            [id] => 10
            [open] => Array
                (
                    [0] => Array
                        (
                            [day] => Monday
                            [start] => 09:00:00
                            [end] => 17:00:00
                        )

                    [1] => Array
                        (
                            [day] => Tuesday
                            [start] => 09:00:00
                            [end] => 17:00:00
                        )

                    [2] => Array
                        (
                            [day] => Thursday
                            [start] => 09:00:00
                            [end] => 17:00:00
                        )
                )
        )
)

当我循环浏览它时,我得到Illegal string offset 'day'

foreach($shops as $shop)
{
    foreach($shop['open'] as $open)
    {
        print_r($open);
        echo $open['day'];
    }
}

print_r($open)显示正确无误:

Array
(
    [day] => Monday
    [start] => 09:00:00
    [end] => 17:00:00
)
我必须做些蠢事。问题是什么?

2 个答案:

答案 0 :(得分:0)

我已经详细编写了这些代码并检查了所有迭代。在第二个循环中,第一次迭代没有day index,它的值是10。你可以查看output

$count=0;
echo "<pre>";
foreach ($shops as $shop) {
    print_r($shop);
    echo "first\n";
    foreach($shop as $open)
    {
        echo "second\n";
        print_r($open);
        if(isset($open[0]))
        {
            foreach ($open as  $value) {
                print_r($value['day']);
            }
        }


    }

}

您也可以查看此代码。并且此代码的​​输出为Here。您还可以在nested foreach loop

中将其拆分
<?php

$shops = Array
(
    0 => Array
        (
            'id' => 10,
            'open' => Array
                (
                    0 => Array
                        (
                            'day' => 'Monday',
                            'start' => '09:00:00',
                            'end' => '17:00:00',
                        ),

                    1 => Array
                        (
                            'day' => 'Tuesday',
                            'start' => '09:00:00',
                            'end' => '17:00:00',
                        ),

                    2 => Array
                        (
                            'day' => 'Thursday',
                            'start' => '09:00:00',
                            'end' => '17:00:00',
                        ),
                )
        )
);


foreach ($shops[0]['open'] as $open) {
    print_r($open['day']);
    echo "<br>";
}

答案 1 :(得分:0)

传入愚蠢:/当我在数组上循环时,我发现最后一个元素没有日,开始或结束 - 只是活跃。因此抛出错误的原因。我只是错过了它,因为数组很大并且它抛出了错误而没有显示任何先前的值,所以我认为它打破了第一个元素。

ReshapeLayerParams