Undefined Offset 0 , how can i set this array

2019-07-26 05:48发布

问题:

Hello i have an Undefined Offset 0 . inside this code.

$q = mysql_query("SELECT * FROM category");
if (false === $q) {
    echo mysql_error();
}

while ($r = mysql_fetch_row($q)) {
  $names[$r[0]] = $r[2];
  $children[$r[0]][] = $r[1];
}

function render_select($root=0, $level=-1) {
  global $names, $children;
  if ($root != 0)
    echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
  foreach ($children[$root] as $child)
    render_select($child, $level+1);
}

echo '<select>';
render_select();
echo '</select>';

The exact line where the error is :

foreach ($children[$root] as $child)
    render_select($child, $level+1);

This is for a selectbox with a tree format, i found this code in this question

More efficient hierarchy system

回答1:

There is some ambiguity in your code here:

if ($root != 0)
    echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
  foreach ($children[$root] as $child)
    render_select($child, $level+1);

If you are attempting to execute these three lines only if $root != 0, you will need to add curly braces like this:

if ($root != 0)
{
    echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
    foreach ($children[$root] as $child)
    {
        render_select($child, $level+1);
    }
}

Otherwise, anytime render_select is called without a parameter (or with a first parameter value of '0') you will attempt to access the element of $children at array key '0'. As your error indicates, $children does not contain a value at that key.