if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id) // = false
但
if($cat[$k]->id==$nav[$lvl-1]->id) // = true
这怎么可能?
您的代码可能是正确的,但您的语句返回false。
你需要调试它。
我将为您写一个如何执行此操作的示例,包括文档。
例:
$test1 = false;
$test2 = null;
$test3 = [];
$test4 = 'asd';
$test5 = 1;
if ($test1)
{
echo 'Valid';
}
else
{
echo 'False';
}
// Output: 'False'
// This is because $test1 = false. The if statement will check if $test1 is set/true and not false.
if ( ! $test2)
{
echo 'NULL';
}
else
{
echo 'NOT NULL';
}
// Output: 'NULL'
// $test2 is NULL/EMPTY (NULL = not valid)
// For the if( ! ..) part, will say if not.
if (is_array($test3))
{
echo 'Is array';
}
else
{
echo 'Is not an array';
}
// Output: 'Is array'
// [] is short for array(); $test3 is an array, so your if statement will continue as valid.
if ( ! empty($test4) || is_integer($test5))
{
echo 'Valid';
}
else
{
echo 'Is not valid';
}
// Output: 'Valid'
// Both $test4 and $test5 pass the if statement. Because $test4 is not empty OR $test5 is an integer.
与您的代码相关:
echo '<pre>';
var_dump($cat[$k]);
echo '</pre>';
die;
if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id);
您需要“调试”您的代码。您需要设置$cat[$k]->id
,如果未设置则返回false。
在调试时,检查数据是否正确解析。
文档:
我希望向您展示如何调试代码并了解isset()
的工作原理,而不是立即给出正确的答案。如果您有疑问,请在评论中告诉我。
祝好运!
我找到了很好的解决方案:对于object属性更好地使用函数property_exists() - http://php.net/manual/en/function.property-exists.php
函数property_exists()返回TRUE,即使该属性的值为NULL。无论如何,感谢用户的评论,更好地知道isset()返回false而不是参数的值为NULL。