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

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

问题描述:

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 ( )

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!.