【问题标题】:Explode database array PHP展开数据库数组 PHP
【发布时间】:2012-04-29 10:07:32
【问题描述】:

我正在尝试将从数据库数组中检索到的段落分解为单独的单词。这是正确的方法吗,因为它当前给出了一个错误,说explode() 需要2 个参数,所以它一定不能拾取$row 数组。

function words() {
        $query = mysql_query("SELECT text FROM table WHERE textID = 1");
        while($row = mysql_fetch_array($query)) {
            $e[] = explode(" ", $row);
            foreach($e as $r) {
                echo $r;
            }
        }
    }

【问题讨论】:

    标签: php arrays explode


    【解决方案1】:
    function words() {
            $query = mysql_query("SELECT text FROM table WHERE textID = 1");
            while($row = mysql_fetch_array($query)) {
                $e[] = explode(" ", $row[0]);
                foreach($e as $r) {
                    echo $r;
                }
            }
        }
    

    $row 是数组。选择要爆炸的第一个元素。阅读Explode 的文档。

    【讨论】:

    • 我错过了那部分。非常感谢。
    【解决方案2】:
    function words() { 
            $query = mysql_query("SELECT text FROM table WHERE textID = 1"); 
            while($row = mysql_fetch_array($query)) { 
                $e[] = explode(" ", $row[0]); 
                foreach($e as $r) { 
                    echo $r; 
                } 
            } 
        } 
    

    【讨论】:

    • mysql_fetch_assoc 将返回带有“文本”字段的数组
    • 哎呀没注意到他正在使用mysql_fetch_array。
    【解决方案3】:

    您在这里使用了错误的功能架构。
    你根本不需要words() 函数。 explode 就够了。
    虽然您强烈需要一个从 mysql 获取数据的函数,这显然与您的爆炸需求无关。
    另请注意,函数不应进行任何输出,而应仅保留值(仅用于输出的函数除外)。

    所以,函数可以是

    function dbgetvar($query){
      $res = mysql_query($query);
      if (!$res) {
        trigger_error("dbget: ".mysql_error()." in ".$query);
        return FALSE;
      }
      $row = mysql_fetch_row($res);
      if (!$row) return NULL;
      return $row[0];
    }
    

    你的代码变得像

    一样简单
    $text  = dbgetvar("SELECT text FROM table WHERE textID = 1");
    $words = explode(" ",$text);
    foreach ($words as $w) echo $w;
    

    【讨论】:

      【解决方案4】:
      function words() {
              $query = mysql_query("SELECT text FROM table WHERE textID = 1");
              while($row = mysql_fetch_array($query)) {
                  $e = explode(" ", $row);
                  foreach($e[0] as $r) {
                      echo $r;
                  }
                  }
          }
      

      $row 完全由字段值填充,因此 $e[0] 是正确的变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 2013-05-28
        • 2015-02-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多