构建数组会给出PHP Undefined Offset:0

时间:2016-09-25 14:29:48

标签: php arrays

我可能找到一种方法来解决我遇到的这个问题,但是我真的很想了解导致它的语言结构。

逻辑如下,我想建立一个Session变量,因为用户点击了谷歌地图上的航路点阵列。 POST数据包是一个JSON对象:

?waypoint={"waypoint":[{"lat":"23.3","long":"145"}]}

接受POST和解释的代码是:

    <?php
     session_start ();
    //session_destroy();
    //die;
    //$waypoints[] = array();  <<== uncomment this and the behaviour changes
    if (isset ( $_GET ['waypoint'] )) {
        $waypoint =  $_GET ['waypoint'];
        $waypoint = json_decode($waypoint,true);
        print_r($waypoint['waypoint']); <<<========output 1
        if (isset ( $_SESSION ['waypoints'] )) {
            $waypoints = $_SESSION ['waypoints'];
            $waypoints [] = $waypoint['waypoint'];
            $_SESSION ['waypoints']=$waypoints;
        } else {
            $_SESSION ['waypoints'] = $waypoint['waypoint']; 
            $waypoints[] = $waypoint['waypoint'];
        }
    }

    foreach( $_SESSION ['waypoints'] as $var) {
        var_dump($var);    <<<<====== Output 2
        echo($var[0]['lat']); <<<<==== Here is the problem.

    };
    ?>

这是问题所在。第一次通过,输出1和2 给出下面的输出,输出的正确值输出= 23.3

  **Output 1:** Array ( [0] => Array ( [lat] => 23.3 [long] => 145 ) )
  -------------------------------------------------------
  **Output 2:**
  array (size=1)
  0 => 
    array (size=2)
      'lat' => string '23.3' (length=4)
      'long' => string '145' (length=3)

第二个调用产生错误Notice: Undefined offset: 0并且后续调用很好,即数组按预期构建。现在,如果我取消注释语句waypoints[] = array();它在第一次通过时就会爆炸,但所有后续运行都没问题。

是否有人能够解释这种行为?

由于

3 个答案:

答案 0 :(得分:4)

你似乎让生活变得比它需要的更复杂。

LANG=ru_RU.UTF-8
$ echo Ю | egrep \w
(nothing)
$ echo Ю | egrep [_[:alnum:]]
Ю
$ echo Ю | egrep '\W\W'
Ю
$ egrep -V
egrep (GNU grep) 2.16

答案 1 :(得分:1)

else {
    $_SESSION ['waypoints'][] = $waypoint['waypoint']; 
}

答案 2 :(得分:1)

问题

您的问题位于else条件的第一行,内容为$_SESSION ['waypoints'] = $waypoint['waypoint'];

修复

如果您将其更改为$_SESSION ['waypoints'][] = $waypoint['waypoint'];,那么您应该解决您遇到的错误。

解释

您在echo($var[0]['lat']);中寻找的内容是每个航路点的包含一个数组,当它们在if中设置时会执行这些数组{{1}条件但不在$waypoints [] = $waypoint['waypoint'];条件(else