dongshi3061 2013-11-21 16:52
浏览 22
已采纳

将对象属性相互比较时,比较失败

I'm encountering an odd issue which should actually be a done deal. My code is not going inside the final loop, even though the data is correct.

<?php
$database->setQuery('SELECT cat_title, cat_id, parent_id FROM #__jdownloads_cats WHERE published = 1 ORDER BY parent_id');      
$cats = $database->loadObjectList();

foreach (array_filter($cats, function($x) { return $x->parent_id == 0; }) as $a) {
    foreach (array_filter($cats, function($x) { return $x->parent_id == $a->cat_id; }) as $b) {             
        // ..
    }           
}
?>

See:

print_r($a); 
stdClass Object
(
    [cat_title] => Category example
    [cat_id] => 1
    [parent_id] => 0
)

and

print_r($cats);
Array
(
    [0] => stdClass Object
        (
            [cat_title] => Category example
            [cat_id] => 1
            [parent_id] => 0
        )

    [1] => stdClass Object
        (
            [cat_title] => Subcategory example
            [cat_id] => 2
            [parent_id] => 1
        )

)

My comparison is failing: $x->parent_id == $a->cat_id. Works as expected if I change to $x->parent_id == 0 or $x->parent_id == 1.

A gettype says those values are strings. What am I missing? TIA.

edit: I don't get it:

echo $a->cat_id == 1 ? "it's 1
" : "its not 1
";

it's 1

print_r(array_filter($cats, function($x) { return $x->parent_id == 1; }));

Array ( [1] => stdClass Object ( [cat_title] => Subcategory example [cat_id] => 2 [parent_id] => 1 )

)

print_r(array_filter($cats, function($x) { return $x->parent_id == $a->cat_id; }));

Array ( )

  • 写回答

1条回答 默认 最新

  • dongliao3450 2013-11-21 17:39
    关注

    It's something I didn't know about PHP:

    You have to explicitly declare variables inherited from the parent scope, with the use keyword.

    So function($x) becomes= function($x) use($a) otherwise everything else is out of scope!.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理