PHP unset多维数组为空的元素
class UnsetEmpty
{
const filter = [[], null, ''];
/**
* @param $arr
* @return array|bool|float|int|string
*/
static public function unsetAllEmpty($arr)
{
if (is_scalar($arr)) {
return $arr;
}
if (is_object($arr)) {
foreach ($arr as $key => $item) {
if (!empty($item)) {
$arr->{$key} = self::unsetAllEmpty($item);
if (in_array($arr->{$key}, self::filter, true)) {
unset($arr->{$key});
}
}
if (in_array($item, self::filter, true)) {
unset($arr->{$key});
}
}
if(empty((array) $arr)){
return [];
}
}
if (is_array($arr)) {
foreach ($arr as $key => $item) {
if (!empty($item)) {
$arr[$key] = self::unsetAllEmpty($item);
if (in_array($arr[$key], self::filter, true)) {
unset($arr[$key]);
}
}
if (in_array($item, self::filter, true)) {
unset($arr[$key]);
}
}
}
return $arr;
}
/**
* @param object $arr
* @return object|null
*/
static public function unsetObjectEmpty(object $arr)
{
foreach ($arr as $key => $item) {
if (!empty($item) && is_object($item)) {
$arr->{$key} = self::unsetObjectEmpty($item);
if (in_array($arr->{$key}, self::filter, true)) {
unset($arr->{$key});
}
}
if (in_array($item, self::filter, true)) {
unset($arr->{$key});
}
}
return $arr;
}
/**
* @param array $arr
* @return array
*/
static public function unsetArrayEmpty(array $arr)
{
foreach ($arr as $key => $item) {
if (!empty($item) && is_array($item)) {
$arr[$key] = self::unsetArrayEmpty($item);
if (in_array($arr[$key], self::filter, true)) {
unset($arr[$key]);
}
}
if (in_array($item, self::filter, true)) {
unset($arr[$key]);
}
}
return $arr;
}
}