PHP Array remove items if missing key
I have the following array format:
Array
(
[0] => st开发者_开发问答dClass 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.
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()
.
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;
}
精彩评论