Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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;
}
share|improve this answer
 
That worked great, just had to use $node->children because of the stdClass –  Russell Jones Oct 18 '10 at 19:33
 
Excellent.. glad it helped out. –  Fosco Oct 18 '10 at 19:37
add comment

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

share|improve this answer
1  
empty() should be used instead of isset(), see php.net/manual/en/function.empty.php example #1 –  David Titarenco Oct 18 '10 at 19:29
 
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 Oct 18 '10 at 19:35
 
@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 Oct 18 '10 at 19:35
 
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 Oct 18 '10 at 19:37
 
@David If you were the one who down-voted both correct answers, can you un-do that please? –  Fosco Oct 18 '10 at 19:40
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.