Undefined Offset 0 , how can i set this array

社会主义新天地 提交于 2019-12-11 04:24:47

问题


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.



来源:https://stackoverflow.com/questions/16470154/undefined-offset-0-how-can-i-set-this-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!