为什么在我的代码if if覆盖值?

时间:2016-02-29 15:40:09

标签: php

<table>
<thead>
<tr>
<th>model</th>
<th>a</th>
<th>jumlah</th>
</tr>

    </thead>
    <?php  foreach((array)$query as $row):
                        if ($row->model='10') {
                            $jumlah=$row->a-10;
                        }else{
                            $jumlah=$row->a-5;
                        };?>
    <td><?php echo $row->model ?></td>
    <td><?php echo $row->a ?></td>
    <td><?php echo $jumlah ?></td>

它应该像这样

enter image description here

但为什么结果会这样?

enter image description here

为什么coloumn模型中的数据超过10? 怎么解决?

3 个答案:

答案 0 :(得分:2)

您正在使用赋值运算符(=)而不是相等运算符(==)。改变这一行:

 if ($row->model = '10') {

到此:

 if ($row->model == '10') {

或者这个:

 if ($row->model == 10) {

在第一种情况下,您告诉编译器存储该值    10变为变量$row->model

在第二种情况下,我们正在检查是否有值    $row->model等于字符串值10.

在第三种情况下,我们正在检查是否有值    $row->model等于10的数值。

我的猜测是,您可能希望使用第三种情况,除非数字作为文本值存储在数据库中。

答案 1 :(得分:1)

php中的

=用于为变量赋值,而==用作比较运算符。

在您的代码中,您需要更改此行:

if ($row->model='10') {

使用:

if ($row->model == '10') {

Here you will find a complete list of PHP operators

答案 2 :(得分:1)

今天出于好心情:

<?php  foreach((array)$query as $row):
                    if ($row->model=='10') { # <- added double = sign
                        $jumlah=$row->a-10;
                    }else{
                        $jumlah=$row->a-5;
                    };?>