未定义的偏移量0,如何设置此数组 [英] Undefined Offset 0 , how can i set this array

查看:138
本文介绍了未定义的偏移量0,如何设置此数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个未定义的偏移量0.在此代码内.

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>';

错误所在的确切行:

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

更有效的层次结构系统

推荐答案

此处的代码中存在一些歧义:

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);

如果仅在$root != 0时尝试执行这三行,则需要添加如下花括号:

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);
    }
}

否则,任何时候只要不带参数(或第一个参数值为'0')调用render_select,您都将尝试在数组键'0'处访问$ children的元素.如您的错误所示,$ children在该键处不包含值.

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.

这篇关于未定义的偏移量0,如何设置此数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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