2012-05-25 58 views
0

我不確定我在訪問PHP中的二維數組時遇到的錯誤。 基本上我的var_dump()給了我下面的:訪問二維數組PHP

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)準備的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是兩個條件中未定義的索引。有什麼不對的嗎?其他指標運行良好,如訪問$ this-> Ns等。 任何想法?

+1

你的原始數組是壞的,它應該是'array(「x」=> 123,「y」=> 234)'而不是2個數組,使用x或y鍵 – MonkeyMonkey

回答

0

更改for循環看起來像這樣:

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

當分配給$points[]沒有索引追加到每一次的陣列。您正在將兩個數組附加到每個循環的$points而不是帶有座標的單個數組。

+0

這個結果非常好。感謝您的快速幫助! :) – Live