php数组返回undefined但print_r显示否则

时间:2015-06-23 07:27:04

标签: php arrays json undefined

foreach($jsonmediationinfo as $value1) {
    echo $value1['mstatus'];
    print_r($jsonmediationinfo);
}

输出:

1Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second [mminutes] => ) [2] => Array ( [mhearingnum] => third [mminutes] => ) ) 

Undefined index: mstatus in ... on line 265第265行是第echo $value1['mstatus'];

这是我的php服务器端代码。这用于将数据保存到数据库中,但我在第265行中未定义index:mstatus。但在print_r中,索引mstatus显然存在。此外,如果我在更新数据时检入数据库,则值会更改为正确的值。在此示例中,值更改为1

这行代码有什么问题。任何建议表示赞赏

2 个答案:

答案 0 :(得分:4)

您正在循环的数组如下所示:

Array (
    [0] => Array (
        [mstatus] => 1
        [mhearingnum] => first
        [mminutes] => adakjaflafjlarjkelfkalfkd;la
    )
    [1] => Array (
        [mhearingnum] => second
        [mminutes] =>
    )
    [2] => Array (
        [mhearingnum] => third
        [mminutes] =>
    )
)

只有第一个索引处的子数组包含mstatus,所以在循环的第二次迭代中它会抛出异常。最好使用mstatus检查isset($value1['mstatus'])是否存在。

foreach ($jsonmediationinfo as $value1) {
    if (isset($value1['mstatus'])) {
        echo $value1['mstatus'];
        print_r($jsonmediationinfo);
    }
}

在现实生活中,你可以像这样处理你的状态:

foreach ($jsonmediationinfo as $value1) {
    if (isset($value1['mstatus']) && ($value1['mstatus'] === 1 || $value1['mstatus'] === true)) {
        // Do something with the positive status
    } else {
        // Do something with the negative/missing status
    }
}

答案 1 :(得分:1)

正如RuubW所说

你也可以像这样处理现实生活中的条件

ADD_LIBRARY