如果语句在 while 循环中

if statement in while loop

本文关键字:循环 while 语句 如果      更新时间:2023-09-26

我有一个PHP脚本,可以从MySQL数据库中的表中获取一些数据。然后它使用 JSON javascript 将此信息发送回 PHP 页面。

这一切都很好用,但我想在 while 循环中做一个 if 语句。我的"已用"表发回"1"和"5",而不是回显 1 或 5,我希望它发送"是"或"否"。

一种方法可能是分解$data并将 1 或 5 替换为"是"或"否"。但是有没有其他方法可以做到这一点?

Something like: `if (used == '1') { set used == 'No } else {set used == 'Yes' }`

我的代码如下

 while ($row = $result->fetch_assoc()) {
    $data['results'][] = array(
        'id' => $row['id'],
        'number' => $row['number'],
        'type' => $row['type'],
        'code' => $row['code'],
        'price' => $row['price'],
        'used' => $row['used'],
        'utime' => $row['utime'],
        'username' => $row['username']
    );
}
//Everything went to plan so set success to true
$data['success'] = true;
//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");
//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);

您可以在数组赋值中使用条件运算符:

'used' => $row['used'] == 1 ? 'Yes' : 'No',

您可以在没有语句的情况下执行此操作if

$answer = array(0 => 'No', 1 => 'Yes');
...
'used' => $answer[ $row['used'] ],
...