簡體   English   中英

檢查關聯數組中的空值

[英]Check for empty values in associative 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);
}

以上輸出:

我把我的1a給2a。
我給1b。

我想讀為:

我把我的1a給2a。
我將我的1b 拒絕輸入

您可以在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);

您應該修改代碼並以這種方式編寫:

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";
    }
}

您可能要嘗試以下操作:

 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);
}

如果您想使其更簡潔一點,則可以將三元運算符提取為如下所示:

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

嘗試:

$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.';
  }
}

只需使用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
}

我這樣寫:

$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";
    });
}

您可以使用以下代碼,也不需要任何額外的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;

這將使用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);

此處使用的其他函數: array_flip()array_intersect_key()count()extract()var_dump()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM