我创建了函数来检查给定键的所有值是否为空。它工作正常,但我想知道这个功能是否可以优化或减少?更好的方法来检查按键是否所有的数组值是空的?
function array_key_empty($array, $key)
{
if (is_array($array)) {
foreach ($array as $item) {
if (array_key_exists($key, $item)) {
if (!empty(trim($item[$key]))) {
return false;
}
}
}
}
return true;
}
例子:
$array = [
['code' => '', 'description' => 'Oh there is a beautiful product !', 'price' => 10],
['code' => '', 'description' => 'Another beautiful product', 'price' => 20],
['code' => '', 'description' => 'Hey where will you stop ?!', 'price' => 30]
];
array_key_empty($array, 'code'); // true because all code are empty
$array = [
['code' => 'Yup !', 'description' => 'Oh there is a beautiful product !', 'price' => 10],
['code' => '', 'description' => 'Another beautiful product', 'price' => 20],
['code' => '', 'description' => 'Hey where will you stop ?!', 'price' => 30]
];
array_key_empty($array, 'code'); // false because Yup...
我投票关闭这一问题作为题外话,因为它应该https://codereview.stackexchange.com/ –
发布哎呀对不起,我忘了代码审查! – Damosse31