我希望能够过滤数组的叶节点,以确保数据按任意规范正确格式化。有没有一种简单的方法将过滤函数应用于PHP中的多维数组的叶节点?
答案 0 :(得分:0)
function filter_leaf_nodes($tree, $filter) {
$ret = array();
foreach ($tree as $subtree) {
if (is_array($subtree)) {
$ret[] = filter_leaf_nodes($subtree, $filter);
} else if ($filter($subtree)) {
$ret[] = $subtree;
}
}
return $ret;
}
$tree = array(
array(
array(
-1,
5
),
-3,
2,
),
array(
3,
9
),
-9
);
$filter = function($node) {
return $node >= 0;
};
var_dump(filter_leaf_nodes($tree, $filter));