简体   繁体   English

Codeigniter奇怪的form_dropdown错误混合索引

[英]Codeigniter weird form_dropdown bug mixed index

I am having a wierd issue with the form_dropdown helper in codeigniter version 2.1.3. 我在Codeigniter 2.1.3版中的form_dropdown帮助器遇到了一个奇怪的问题。

The following code: 如下代码:

print_r($country_options);

echo form_label('Country:','country') . 
form_dropdown('country',$country_options, 0);
...

Outputs 产出

Array ( [0] => All [Australia] => Australia )

<label for="country">Country:</label>
<select name="country">
<option value="0" selected="selected">All</option>
<option value="Australia" selected="selected">Australia</option>
</select>

What am I not seeing? 我没看到什么?

The problem that instead of only the dropdown 'All' being selected as is set in the third parameter of the form_dropdown function, both dropdown options are being selected even though the second option has a key of 'Australia' 问题,而不是仅在form_dropdown函数的第三个参数中设置了下拉菜单“ All”,而是选择了两个下拉选项,即使第二个选项的键为“ Australia”

This is a peculiarity in php's in_array function; 这是php in_array函数的特性; unfortunately, I can't completely explain it to you, but it revolves around your using the 0 as a key: 不幸的是,我无法完全向您解释它,但是它围绕您使用0作为键:

The code in the form_helper is: form_helper中的代码是:

$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';

where $key = 'Australia' & $selected is actually an array, array(0=>0); $ key ='Australia'&$ selected实际上是一个数组,array(0 => 0);

Now, where the weirdness in php occurs is: 现在,php中发生怪异的地方是:

Anytime you use a key that will evaluate to false (ie, false, 0, '') you will end up matching all string values. 每当您使用计算结果为false的键(即false,0,'')时,最终都会匹配所有字符串值。 You can play around with different arrays and see. 您可以尝试使用不同的数组来查看。

So, do as Deepanshu recommended & use Array ( [0] => All [1] => Australia ) 因此,按照Deepanshu的建议进行操作并使用Array([0] =>所有[1] =>澳大利亚)

EDIT: More investigation shows that reason is not 100% correct, but the solution is still valid. 编辑:更多调查显示原因并非100%正确,但解决方案仍然有效。 I think the issue is simply that the string is being evaluated as a 0 when compared to the array values 我认为问题很简单,与数组值相比,字符串被评估为0

More info: Why does PHP consider 0 to be equal to a string? 更多信息: 为什么PHP认为0等于字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM