【问题标题】:Accessing two dimensional arrays PHP访问二维数组 PHP
【发布时间】:2012-06-01 09:19:52
【问题描述】:

我不确定在 PHP 中访问二维数组时遇到的错误。 基本上我的 var_dump() 给了我以下信息:

 array(1) {
   ['x']=>
     string(1) "3"
 }
 array(1) {
   ['y']=>
     string(3) "3"
 }

 array(1) {
   ['x']=>
     string(1) "5"
 }
 array(1) {
   ['y']=>
     string(3) "5"
 }

var_dump 是正确的,并且显示了我想要达到的结果。

我正在做的事情如下: 1) 在 $points 数组中准备 x 和 y 坐标 2)检查一些数字是否在给定的坐标内:

    function check_collisions {
    $points = array();
    for($y = 0; $y < count($this->Ks); $y++)
    {
        $points[]['x'] = $this->Ks[$y][0]; // first is 3, second is 5 - see var_dump above
        $points[]['y'] = $this->Ks[$y][1]; // first is 3, second is 5 - see var_dump above
    }


    for($p = 0; $p < count($points); $p++)
    {
        for($r = 0; $r < count($this->Ns); $r++)
        {
            if($points[$p]['x'] >= $this->Ns[$r][0] && $points[$p]['x'] <= $this->Ns[$r][2])
            {

                if($points[$p]['y'] >= $this->Ns[$r][1] && $points[$p]['y'] <= $this->Ns[$r][3])
                {

                    $collisions++;
                }
            }
        }
    }
    return $collisions;
    }

我的 PHP 现在告诉我 x 和 y 是两个 if 条件中的未定义索引。有什么问题吗?其他索引运行良好,例如访问 $this->Ns 等。 有什么想法吗?

【问题讨论】:

  • 你原来的数组是坏的,应该是array("x" =&gt; 123, "y" =&gt; 234)而不是2个带有x或y键的数组

标签: php arrays multidimensional-array


【解决方案1】:

将您的 for 循环更改为如下所示:

for($y = 0; $y < count($this->Ks); $y++)
{
    $points[] = array('x' => $this->Ks[$y][0], 'y' => $this->Ks[$y][1]);
}

当您分配给没有索引的$points[] 时,它每次都会附加到数组中。您将两个数组附加到 $points 每个循环而不是带有坐标的单个数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多