简体   繁体   English

检查数组的键是否为null或空字符串的值

[英]Check array's key for it's value for null or empty string

I have an array from mysql that I want to echo through variables. 我有一个mysql数组,我想通过变量回显。 I want the raw array to have checked for any null or empty strings to be set as the string " <null> " for personal reasons. 我希望原始数组检查是否出于个人原因将任何null或空字符串设置为字符串“ <null> ”。 But i can't seem to get the expected result. 但我似乎无法获得预期的结果。 Thanks in advance. 提前致谢。

while ($row = mysql_fetch_array($RS2)) {
    foreach ($row as $key => $value) {
        if (empty($value)) {
            $row[$key] = "<null>";
        }
    }
        echo "serno=$row[serno];";
        echo "date=$row[date];";
        echo "time=$row[time];";
        echo "nett=$row[nett];";
        echo "amount=$row[amt];";
        echo "\n";
}

The current outcome when echo out currently looks like this: echo out当前的结果如下所示:

serno=1003;date=2018-07-14;time=01:18:57;nett=;amount=500.00;

Expected outcome is: 预期结果是:

serno=1003;date=2018-07-14;time=01:18:57;nett=<null>;amount=500.00;

User foreach loop as below: 用户foreach循环如下:

foreach ($row as $key => $value) {
    $row[$key] = empty($value) ? "" : $value;
}

It will replace empty values to "" . 它会将空值替换为""

//I forgot to put else    
$otherArray = array();
while ($row = mysql_fetch_array($RS2)) {
    foreach ($row as $key => $value) {
        if (empty($value)) {
            $otherArray[$key] = "<null>";
        }else{//else here
            otherArray[$key] = $value;
    }

}
    echo "serno=$otherArray[serno];";
    echo "date=$otherArray[date];";
    echo "time=$otherArray[time];";
    echo "nett=$otherArray[nett];";
    echo "amount=$otherArray[amt];";
    echo "\n";

} }

You can use a built in function is_null 您可以使用内置函数is_null

while ($row = mysql_fetch_array($RS2)) {
    foreach ($row as $key => $value) {
        if (is_null($value)) {
            $var="<null>";
            $row[$key] = htmlspecialchars($var);
        }
    }
        echo "serno=$row[serno];";
        echo "date=$row[date];";
        echo "time=$row[time];";
        echo "nett=$row[nett];";
        echo "amount=$row[amt];";
        echo "\n";
}
//may be like that 
$otherArray = array();
while ($row = mysql_fetch_array($RS2)) {
    foreach ($row as $key => $value) {
        if (empty($value)) {
            $otherArray[$key] = "<null>";
        }
        otherArray[$key] = $value;
    }
    echo "serno=$otherArray[serno];";
    echo "date=$otherArray[date];";
    echo "time=$otherArray[time];";
    echo "nett=$otherArray[nett];";
    echo "amount=$otherArray[amt];";
    echo "\n";
}
foreach($row as $key => $value){
     $row[$key] = !isset($value) ? NULL : $value; }

Use the isset So it easily check for the NULL values 使用isset因此它可以轻松检查NULL值

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

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