简体   繁体   English

检查关联数组中的空值

[英]Check for empty values in associative array

I'm having a hard time checking for empty values in my associative array. 我很难检查关联数组中的空值。 And if a value is empty/null replace it with the wording "not entered" 如果值是空/空,则将其替换为“未输入”

My $_SESSION['gift'] array: 我的$ _SESSION ['gift']数组:

Array
(
    [0] => Array
        (
            [giftGiveMy] => 1a
            [giftTo] => 2a
        )

    [1] => Array
        (
            [giftGiveMy] => 1b
            [giftTo] => '' //### empty ###
        )

)



 if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
    $gifts = "No specific gifts identified.\n";
 } else {
    $gifts = [];
    foreach( $_SESSION['gift'] as $value) {
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $value['giftTo'] .".\n";
    }
    $gifts = join($gifts);
}

The above outputs: 以上输出:

I give my 1a to 2a. 我把我的1a给2a。
I give my 1b to . 我给1b。

I would like it read: 我想读为:

I give my 1a to 2a. 我把我的1a给2a。
I give my 1b to not entered . 我将我的1b 拒绝输入

You can replace all empty and NULL value with not entered with the help of array_walk_recursive and use you code as it is 您可以在array_walk_recursive的帮助下将所有空值和NULL值替换为not entered ,并按原样使用您的代码

 array_walk_recursive($arrayMain, 'not_entered');

    function not_entered(& $item, $key) {
    if (($item === "") || ($item ==NULL)){
        $item = "not entered";
    }
}
var_dump($arrayMain);

You should modify your code and write it this way: 您应该修改代码并以这种方式编写:

if (!isset($_SESSION['gift']) || empty($_SESSION['gift'])) {

     $gifts = "No specific gifts identified.\n";

} else {

    foreach( $_SESSION['gift'] as $value) {

        $gift_to = !empty($value['giftTo']) ? $value['giftTo'] : '<strong>Not entered<strong>';
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $gift_to .".\n";
    }
}

You might want to try this: 您可能要尝试以下操作:

 if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
    $gifts = "No specific gifts identified.\n";
   } else {
    $gifts = [];
    foreach( $_SESSION['gift'] as $value) {
        $gifts[] = "I give my ". $value['giftGiveMy'] ." to ". (!empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>') .".\n";
    }
    $gifts = join($gifts);
}

If you would like to make it a little cleaner you could extract the ternary operator into something like this; 如果您想使其更简洁一点,则可以将三元运算符提取为如下所示:

$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : '<b>not  entered</b>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $giftTo .".\n";

Try: 尝试:

$arr =  $_SESSION['gift'];
foreach($arr as $key => $array) {
  if($array['giftGiveMy'] == null || empty($array['giftGiveMy'])) {
    $arr[$key]['giftGiveMy'] = 'not entered.';
  }
  if($array['giftTo'] == null || empty($array['giftTo'])) {
    $arr[$key]['giftTo'] = 'not entered.';
  }
}

Just use foreach to loop all values and check if it's empty 只需使用foreach循环所有值并检查其是否为

$emptyText = '<b>not entered</b>';

// `empty` will also be true if element does not exist 
if (empty($_SESSION['gift'])) {
    $gifts = "No specific gifts identified.\n";
} else {
    $gifts = [];

    foreach($_SESSION['gift'] as $value) {
        $myGive = !empty($value['giftGiveMy']) ? $value['giftGiveMy'] : $emptyText;
        $giftTo = !empty($value['giftTo']) ? $value['giftTo'] : $emptyText;
        $gifts[] = "I give my {$myGive} to {$giftTo}.";
    }

    $gifts = implode("\r\n", $gifts); // Or `<br/>` if outputted to HTML
}

I'd write that this way: 我这样写:

$gifts = "No specific gifts identified.\n";

$filter = function($str) {
               return empty($str) ? 'not entered' : $str;
          };

if(!empty($_SESSION['gift'])) {
    $gifts = '';
    array_walk($_SESSION['gift'], function($given) use(&$gifts,$filter){
        $gifts .= 'I give my ' . $filter($given['giftGiveMy']) . ' to ' . $filter($given['giftTo']) . ".\n";
    });
}

You can use for the below code also there is no need any extra Php functions. 您可以使用以下代码,也不需要任何额外的Php函数。

$arr = array(
    0 => array(
        'giftGiveMy' => '1a',
        'giftTo' => '2a'
    ),
    1 => array(
        'giftGiveMy' => '1b',
        'giftTo' => ''
    )
);

$str = '';
if (!empty($arr)) { 
    foreach ($arr as $key => $value) {
        if ($value['giftGiveMy'] == '')
            $value['giftGiveMy'] = 'not entered';
        if ($value['giftTo'] == '')
            $value['giftTo'] = '<strong>not entered</strong>';
        //$new[$key] = $value;
        $str .= "I give my " . $value['giftGiveMy'] . " to " . $value['giftTo'] . "<br />";
    }
}else {
    $str = 'No specific gifts identified.<br />';
}

echo $str;

This validates an associative array with empty() (see array_filter ), but may not respond to the original question. 这将使用empty()验证一个关联数组(请参阅array_filter ),但可能不会响应原始问题。

<?php

$var = array();
$var['position'] = 'executive';
$var['email'] = 'a@email.com';
$var['message'] = 'This is the message';
$var['name'] = 'John Doe';
$var['telephone'] = '123456789';
$var['notneededparam'] = 'Nothing';

$expectedParams = ['position', 'email', 'message', 'name', 'telephone'];

$params = array_intersect_key($var, array_flip($expectedParams));

// check existence of keys and that they are valid
if(count($params) != count($expectedParams) || count(array_filter($params)) != count($expectedParams)){
    echo "not valid\n";
    die();
}

extract($params);

var_dump($name);

Other functions used here: array_flip() , array_intersect_key() , count() , extract() , var_dump() , 此处使用的其他函数: array_flip()array_intersect_key()count()extract()var_dump()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM