dougang2749 2011-02-17 18:18
浏览 11
已采纳

PHP中的逻辑问题

Ok, i tested what follows and i'll just let you know what i discovered:

echo ('-1' < 0) ? 'true' : 'false'; // will echo "true"
echo ('1' > 0) ? 'true' : 'false'; // will echo "true"
# Notice that '-1' and '1' are strings

Now let's take an array, coming from the database after filtering all the result in order to get only rows with UID = 1.

$this->a = array(
    [0] => array(
        'UID' => '1',
        'PID' => '91',
        'Amount' => '-1'
    ),
    [1] => array(
        'UID' => '1',
        'PID' => '92',
        'Amount' => '1'
    ),
    [2] => array(
        'UID' => '1',
        'PID' => '93',
        'Amount' => '1'
    )
);

Now i want to create a function posAmount($PID) that returns true if 'Amount' > 0 or false if 'Amount' < 0. (Notice: Amount = 0 is something i don't really care). Also i'd like to write as similar function called negAmount($PID) that returns the exactely opposite of the first. I'd like, now, to introduce you to my twin functions:

public function posAmount($pid)
{
    foreach ($this->a as $a)
    {
        if (count($this->a) == 0) { return false; }
        return ($a['PID'] == $pid and $a['Amount'] > 0) ? true : false;
    }
}

public function negAmount($pid)
{
    foreach ($this->a as $a)
    {

        if (count($this->a) == 0) { return false; }
        return ($a['PID'] == $pid and $a['Amount'] < 0) ? true : false;
    }
}

The cool fact is that, regarding the first array (which, i checked with var_dump() keeps its nature trough the entire script):

$istance->negAmount(91); // Returns true, as expected
$istance->posAmount(92); // Returns false, as NOT expected.
# Why do God wants me to get mad?
  • 写回答

4条回答 默认 最新

  • douyong5825 2011-02-17 18:25
    关注

    The problem is that you are always returning on the first iteration of the foreach loop. You should rewrite the functions like this:

    public function negAmount($pid) {
        if (count($this->a) == 0) { return false; }
        foreach ($this->a as $a) {
            if ($a['PID'] == $pid) {
                if ($a['Amount'] < 0) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public function posAmount($pid) {
        if (count($this->a) == 0) { return false; }
        foreach ($this->a as $a) {
            if ($a['PID'] == $pid) {
                if ($a['Amount'] > 0) {
                    return true;
                }
            }
        }
        return false;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP