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

h7appiyu  于 2021-06-20  发布在  Mysql
关注(0)|答案(5)|浏览(374)

我有一个来自mysql的数组,我想通过变量回送它。我想让原始数组检查是否有空字符串或空字符串被设置为字符串“ <null> “出于个人原因。但我似乎没有得到预期的结果。提前谢谢。

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

echo out当前的结果如下所示:

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

预期结果是:

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

bq3bfh9z1#

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

}

pxy2qtax

pxy2qtax2#

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

np8igboo3#

foreach($row as $key => $value){
     $row[$key] = !isset($value) ? NULL : $value; }

使用isset,以便轻松检查空值

b0zn9rqh

b0zn9rqh4#

可以使用内置函数 is_null ```
while ($row = mysql_fetch_array($RS2)) {
foreach ($row as $key => $value) {
if (is_null($value)) {
$var="";
$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";
}

b1payxdu

b1payxdu5#

用户foreach循环如下:

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

它将把空值替换为 "" .

相关问题