访问二维数组 PHP [英] Accessing two dimensional arrays PHP

查看:78
本文介绍了访问二维数组 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not sure about an error I'm getting while accessing a two-dimensional array in PHP. Basically my var_dump() gives me the following:

 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 是正确的,并显示了我想要达到的结果.

The var_dump is imho correct and shows the results I wanted to achieve.

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

What I'm doing is the following: 1) preparing x and y coordinates within an $points array 2) check if some numbers are within the coordinates given:

    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 等.有什么想法吗?

My PHP now tells me that x and y are undefined indexes within the two if conditions. Is there anything wrong? The other indexes are working well, like accessing $this->Ns etc. Any ideas?

推荐答案

for 循环更改为如下所示:

Change your for loop to look like this:

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

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

When you assign to $points[] with no index it appends to the array every time. You are appending two arrays to $points each loop instead of a single array with the coordinates.

这篇关于访问二维数组 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆