共計(jì) 529 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
可以使用遞歸函數(shù)來(lái)遍歷多維數(shù)組,將空值去除。
以下是一個(gè)示例代碼:
function removeEmptyValues(&$array) {foreach ($array as $key => &$value) {if (is_array($value)) {removeEmptyValues($value);
} else {if (empty($value)) {unset($array[$key]);
}
}
}
}
使用示例:
$array = array(
'name' => 'John',
'age' => '','address'=> array('street'=>'123 Main St','city'=>'',
'state' => 'CA'
)
);
removeEmptyValues($array);
print_r($array);
輸出結(jié)果:
Array
([name] => John
[address] => Array
([street] => 123 Main St
[state] => CA
)
)
在示例中,遞歸函數(shù) removeEmptyValues
遍歷多維數(shù)組,如果值是一個(gè)數(shù)組,則遞歸調(diào)用該函數(shù)繼續(xù)遍歷。如果值是一個(gè)空值,則使用 unset
函數(shù)將其從數(shù)組中刪除。最終,只剩下非空值的數(shù)組。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完