【问题标题】:Comparing array value (int) from database to an integer in if statement将数据库中的数组值(int)与if语句中的整数进行比较
【发布时间】:2013-06-11 09:32:15
【问题描述】:

这个问题相当简单,但很难完全解释。我正在从数据库中提取数据“url”和“section”。 'section' 值是一个整数。我将所有这些数据拉到另一个数组中以显示到另一个页面上。 (这是一个站点地图生成器)

<?php 

$query = "SELECT url, section FROM table WHERE section <= 3";
    $result = db_query($query, $dbh);

    $dynamic_urls = array();
    while ($row = db_fetch_array($result))
    {
    $dynamic_urls[] = "http://example.com/" . checkSection() . $row['url'];
    }

    function checkSection(){
        if ($row['section'] == 1)
        {
            return "web/";
        } 
        elseif ($row['section'] == 2)
        {
            return "email/";
        } 
        elseif ($row['section'] == 3){
            return "print/";
        }
        return "FAILED/";
    }

    ?>

我认为问题在于 checkSection() 方法在将数组值 $row['section'] 与整数 (1, 2, 3) 进行比较时遇到问题,如图所示。输出文件只是遍历数组 $dynamic_urls 并将它们打印到一个页面,这里是一些示例输出:

http://example.com/FAILED/example_permalink1

http://example.com/FAILED/example_permalink2

http://example.com/FAILED/example_permalink3

http://example.com/FAILED/example_permalink4

http://example.com/FAILED/example_permalink5

http://example.com/FAILED/example_permalink6

我需要那些“失败”输出是我正在寻找的相关“网络/”、“电子邮件/”或“打印/”标题。

为什么我的 if 语句无法将 $row['section_id'] 与整数进行比较?

【问题讨论】:

  • 您需要将$row 传递给checkSection() - 它超出了范围。
  • 那么,将 checkSection 的初始声明更改为 checkSection($row) 有效吗?或 checkSection($row['section_id'])?
  • @andrewsi 成功了!谢谢!
  • 前者会这样做 - 请参阅 Kelly John Rose 的答案

标签: php if-statement integer comparison sitemap


【解决方案1】:

问题是你的行没有在你的函数范围内被接收。

function checkSection(){
    if ($row['section'] == 1)
    {
        return "web/";
    } 
    elseif ($row['section'] == 2)
    {
        return "email/";
    } 
    elseif ($row['section'] == 3){
        return "print/";
    }
    return "FAILED/";
}

对于函数,$row 是空白的。您需要将其作为变量传递给函数才能正常工作。

即。

function checkSection($row){
    if ($row['section'] == 1)
    {
        return "web/";
    } 
    elseif ($row['section'] == 2)
    {
        return "email/";
    } 
    elseif ($row['section'] == 3){
        return "print/";
    }
    return "FAILED/";
}

checkSection($row)

【讨论】:

  • 谢谢。那行得通。我晚上需要多睡觉,我一直在摇头,想知道我做错了什么。
  • 没问题,当您从功能的角度开始使用 PHP 时,这是一个非常容易犯的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2013-11-10
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多