1

我无法弄清楚这里的问题是什么。我有一个带有预定义索引的关联数组,当尝试访问其中一个索引时,出现未定义索引错误,这是代码,

        if(!isset($score_value[$index])){
            echo $index . ' isnt in array: <br/>';
            print_r($score_value);
            exit;
        }
        print_r($score_value[$index]);

输出是这样的:

pi_cholesterol不在数组中:

Array ( 
    [pi_overall_health] => Array ( 
        [4] => 4 [1] => 1 [2] => 4 [3] => 1 
    ) 
    [pi_bmi] => Array ( 
        [Healthy Weight] => 4 [Obese] => 3 [Overweight] => 3 
    ) 
    [pi_cholesterol] => Array ( 
        [Yes - its level is too high] => 6 [Yes - its level is ok] => 3 [No] => 1 
    ) 
)

如您所见pi_cholesterol,它是数组中的一个索引,但由于某种原因isset()将其标记为不在数组中,如果我尝试使用array_key_exists(). 我可能忽略了一些简单的事情,但我看不到它。

欢迎任何建议!

4

1 回答 1

0

对不起我自己的愚蠢错误, $index 在代码的另一个地方被覆盖,并被附加了一个尾随空格。

Mjh、axiac 和 rahul_m 建议使用 trim() 帮助我解决了这个问题。

于 2017-05-11T11:39:54.993 回答