PHP:Can';在数组中找不到关键字


PHP: Can't find key in Array

我的脚本有问题。我有这个阵列:

Array
(
    [KUNDENNUMMER] => 
    [BEZ] => 
    [DATUM] => 2014-10-10
    [VON] => 11:10:36
    [BIS] => 11:48:11
    [TAETIGKEIT] => Berufschule
    [BEZ_01] => 
    [DAUER] => 0001-01-01 00:37:00
    [STUNDEN] => 0.61
    [VERRECHENBAR] => F
    [BEMERKUNG] => 0x000c5cf2000000ba
    [USER_BEZ] => Armani, Kia
    [TZ_BEZ] => 
    [TT_VERRECHENBAR] => F
    [TT_ID] => 80
)

当$row(数组)[TATEGKEIT]==Berufschule使用此代码时,我想回显"Cake"

if(strpos($row['TAETIGKEIT'], 'Berufschule') === true) echo "Cake";

但回声永远不会被调用。我也试着直接比较

if($row['TAETIGKEIT'] == 'Berufschule') echo "Cake";

但它也不起作用。当我做时

print_r($row['TAETIGKEIT'];

它打印

Berufschule

我做错了什么?

总结一下,可能由于各种原因,有问题的代码无法工作。

我只能假设TAETIGKEIT的值有一个尾随空格或先行空格。

if(strpos($row['TAETIGKEIT'], 'Berufschule') === true) echo "Cake";
// doesn't work since strpos returns an integer if string is found or `false` if not.
// it never returns true
if($row['TAETIGKEIT'] == 'Berufschule') echo "Cake";
// doesn't work due to the superfluous space, thus it's not exactly the same

解决方案是正确使用strpos

if(strpos($row['TAETIGKEIT'], 'Berufschule') !== false) echo "Cake";

或者在比较之前修剪值

if(trim($row['TAETIGKEIT']) == 'Berufschule') echo "Cake";

正如h2ooooooooo所指出的,var_dump将显示这些加法空间。

strpos从不返回true-它返回false或整数值,因此使用=== true永远不会通过。

试试看:

strpos($row['TAETIGKEIT'], 'Berufschule') !== false