如何摆脱PHP未定义的偏移错误?

时间:2022-04-29 20:19:23

How to get rid of error: Undefined offset: 1 on line 20? I know it occurs becaouse Im calling array that's offset simply does not exist.

如何摆脱错误:未定义的偏移量:第20行的1?我知道它发生了因为我调用数组的偏移根本就不存在。

Silecing it wiht @ just doesnt seem right at all.

和@一起消磨它似乎根本不对。

//create an array with all x, y
for ($x = 1; $x <= 5; $x++) $array_x[] = $x;
for ($y = 1; $y <= 5; $y++) $array_y[] = $y;

$IN_x = "'" . implode("', '", $array_x) . "'";
$IN_y = "'" . implode("', '", $array_y) . "'";

$pullMapInfo = "SELECT x, y, value FROM mapinfo WHERE id='{$id}' AND x IN ({$IN_x}) AND y IN ({$IN_y})";
$pullMapInfo2 = mysql_query($pullMapInfo) or die('error here');

//create an associative array x, y => value
while ($pullMapInfo3 = mysql_fetch_assoc($pullMapInfo2)) {
    $result[ $pullMapInfo3['x'] ][ $pullMapInfo3['y'] ] = $pullMapInfo3['value'];
}

//loop to display output
foreach ($array_x as $x) {
foreach ($array_y as $y) {
    if (array_key_exists($x, $result) && array_key_exists($y, $result)) {
        echo '<div class="castle_array" id="'.$x,'x',$y.'">'. $result[$x][$y] .'</div>
                ';
    } else {
        echo '<div class="castle_array" id="'.$x,'x',$y.'"></div>
                ';
    }
}
}

2 for loops seems awkard

2 for for循环似乎很尴尬

2 个解决方案

#1


0  

Your second call to array_key_exists should pass in $result[$x]:

你对array_key_exists的第二次调用应传入$ result [$ x]:

if ( array_key_exists($x, $result) && array_key_exists($y, $result[$x]) ) {
    // Code goes here...
}

#2


2  

Replace this line:

替换此行:

if (array_key_exists($x, $result) && array_key_exists($y, $result)) {

with:

if (isset($result[$x][$y])) {

Documentation: isset

For Joseph Silber: Try this PHP fiddle

对于Joseph Silber:试试这个PHP小提琴

#1


0  

Your second call to array_key_exists should pass in $result[$x]:

你对array_key_exists的第二次调用应传入$ result [$ x]:

if ( array_key_exists($x, $result) && array_key_exists($y, $result[$x]) ) {
    // Code goes here...
}

#2


2  

Replace this line:

替换此行:

if (array_key_exists($x, $result) && array_key_exists($y, $result)) {

with:

if (isset($result[$x][$y])) {

Documentation: isset

For Joseph Silber: Try this PHP fiddle

对于Joseph Silber:试试这个PHP小提琴