tags:

views:

55

answers:

2

I have the following array format:

Array
(
    [0] => stdClass Object
        (
            [tid] => 3
            [children] => Array ()
        )
    [1] => stdClass Object
        (
            [tid] => 15
        )
    [2] => stdClass Object
        (
            [tid] => 12
            [children] => Array ()
        )
    [3] => stdClass Object
        (
            [tid] => 9
            [children] => Array ()
        )
)

I would like to remove items that do not have [children] and am having some difficulty doing so.

Help is appreciated, thank you.

+2  A: 

Try this, where $array is the array you want to process

foreach($array as $key => $value)
{
    if(!isset($value['children'])
        unset($array[$key]);
}

This will remove all items in your array where children is not set or is null. Since in your example you set children to empty arrays, you will need to use isset() and not empty().

Alan Geleynse
`empty()` should be used instead of `isset()`, see http://php.net/manual/en/function.empty.php example #1
David Titarenco
That depends on what the desired behavior is. `empty` will remove all values where `children` is a element, but is set to null or an empty array. `isset` will do not remove the values if children is an empty array but is `null`, and `array_key_exists` will not remove any values where children is set to anything, even `null`.
Alan Geleynse
@David I disagree. Not only is `isset()` correct for the given example, I can't think of anywhere I would choose to use `empty()`
Fosco
I misunderstood the question and deleted my answer, isset would work fine in this case :) to check whether or not an array is empty, however, `empty()` (not isset) should be used.
David Titarenco
@David If you were the one who down-voted both correct answers, can you un-do that please?
Fosco
I didn't downvote either.
David Titarenco
+1  A: 

Can you give this a shot and let me know what happens?

$myArray = array_filter($myArray, "hasChildren");

function hasChildren($node) {
    if (isset($node->children)) return true;
    return false;
}
Fosco
That worked great, just had to use $node->children because of the stdClass
roosta
Excellent.. glad it helped out.
Fosco