无法从php数组中获取值

时间:2011-07-22 06:22:38

标签: php arrays

这是我的php代码

 echo '<pre>';
 print_r($weekdays); echo '<br/>';

 foreach ($weekdays as $key => $day) {

     print_r($day); echo '<br/>';
     echo 'key - '. $key; echo '<br/>';
     echo 'val - '. $day['val']; die;      
 }

这是

的结果
Array
(
[sunday] => Array
    (
        ['val'] => 1
        ['from'] => 6:00:00
        ['to'] => 6:00:00
    )

[monday] => Array
    (
        ['val'] => 1
        ['from'] => 6:00:00
        ['to'] => 6:00:00
    )

[tuesday] => Array
    (
        ['from'] => 7:00:00
        ['to'] => 0:00:00
    )

[wednesday] => Array
    (
        ['from'] => 0:00:00
        ['to'] => 0:00:00
    )

[thuesday] => Array
    (
        ['from'] => 0:00:00
        ['to'] => 0:00:00
    )

[friday] => Array
    (
        ['from'] => 0:00:00
        ['to'] => 0:00:00
    )

[saturday] => Array
    (
        ['from'] => 0:00:00
        ['to'] => 0:00:00
    )
)

Array
(
['val'] => 1
['from'] => 6:00:00
['to'] => 6:00:00
)

key - sunday
val - 

问题出现在我的foreach中,我试图获得$day['val'],但没有显示。尝试使用$ day-&gt; val。当我print_r($day)我得到

Array
(
['val'] => 1
['from'] => 6:00:00
['to'] => 6:00:00
)

请帮帮我。

3 个答案:

答案 0 :(得分:4)

问题是该密钥不是val它是'val'(带引号)。

echo 'val - '. $day["'val'"];

会工作。

答案 1 :(得分:1)

您的密钥似乎实际为'val',而不是val

答案 2 :(得分:1)

我想最好确保你没有用撇号命名数组键。这可能会使您将来或使用此代码的人感到困惑。

您的print_r应如下所示:

Array ( 
    [sunday] => Array
       (
          [val] => 1
          [from] => 6:00:00
          [to] => 6:00:00
       )

更正创建该数组的代码,然后设置。