if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id) // = false
但是
if($cat[$k]->id==$nav[$lvl-1]->id) // = true
怎么可能?
答案 0 :(得分:0)
您的代码可能正确,但是您的语句返回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()
的工作原理,而不是立即给您正确的答案。如果您有任何疑问,请在评论中告诉我。
祝你好运!
答案 1 :(得分:0)
我找到了很好的解决方案:为了使对象属性更好地使用function property_exists()-http://php.net/manual/en/function.property-exists.php
即使属性的值为NULL,函数property_exists()也会返回TRUE。无论如何,感谢用户的评论,最好知道isset()返回false而不是参数具有NULL值。