检查关联数组中的空值

问题描述 投票:0回答:8

我很难在关联数组中检查空值。如果值为空/ null则将其替换为“未输入”的措辞

我的$ _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没有进入。

php associative-array
8个回答
1
投票

只需使用foreach循环所有值并检查它是否为empty

$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
}

2
投票

您可以在not entered的帮助下用array_walk_recursive替换所有空值和NULL值并使用代码,因为它是

 array_walk_recursive($arrayMain, 'not_entered');

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

1
投票

您应该修改您的代码并以这种方式编写它:

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

1
投票

你可能想试试这个:

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

1
投票

尝试:

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

1
投票

我这样写:

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

0
投票

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

0
投票

这将使用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()

© www.soinside.com 2019 - 2025. All rights reserved.