检查按键的所有数组值是否为空的更好方法是?

时间:2017-08-08 09:51:02

标签: php arrays optimization key

我创建了一个函数来检查给定键的所有值是否为空。它工作正常,但我想知道这个功能是否可以优化或减少?

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...

2 个答案:

答案 0 :(得分:1)

你可以这样做: -

if(count(array_filter( array_map('trim',array_column($array,'code'))))==0){
  echo "all values are empty";
}

输出: - https://eval.in/842810

答案 1 :(得分:1)

你可以将你的功能减少到一行,如下所示:

git checkout

<强>输出:

<?php

$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]
];


function array_key_empty($array, $key)
{
     return is_array($array) && empty(array_map('trim', array_filter(array_column($array, $key))));
}

echo "<pre>";
print_r(array_key_empty($array, 'code'));