2017-08-08 19 views
0

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

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

我投票关闭这一问题作为题外话,因为它应该https://codereview.stackexchange.com/ –

+0

发布哎呀对不起,我忘了代码审查! – Damosse31

回答

1

你可以像下面: -

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

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

+0

谢谢!卜我需要修剪每个值,在这种情况下,如果一个值包含它认为没有空的空间。 – Damosse31

+0

@ Damosse31让我补充一点 –

+0

@ Damosse31立即查看 –

1

您可以将功能减少到单行像这样:

<?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')); 

输出:

1 
相关问题