【发布时间】:2018-01-15 19:58:36
【问题描述】:
我创建了一个函数来检查给定键的所有值是否为空。它工作正常,但我想知道这个功能是否可以优化或减少?
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...
【问题讨论】:
-
我投票结束这个问题,因为它应该发布在codereview.stackexchange.com
-
抱歉,我忘记了 codereview !
标签: php arrays optimization key