【问题标题】:PHP Warning: Illegal string offset '' while iterating through an arrayPHP 警告:在遍历数组时出现非法字符串偏移 ''
【发布时间】:2020-08-17 06:31:48
【问题描述】:

尝试迭代数组时,我不断收到“警告:非法字符串偏移”错误。

使用 var_dump 后的结果 ---> array(19) { ["id"]=> int(1) ["handle"]=> string(4) "test" ["blockname"]=> string(0) "" ["project"]=> string(0) "" ["document_description"]=> string(4) "test" ["project_id"]=> string(0) "" ["revision"]=> string(0) "" ["scale" ]=> string(0) "" ["document_num"]=> string(9) "test-1557" ["drawn_by"]=> string(0) "" ["approved_by"]=> string(0) " " ["checked_by"]=> string(0) "" ["issued_by"]=> string(0) "" ["drawn_date"]=> string(0) "" ["approved_date"]=> string(0 ) "" ["checked_date"]=> string(0) "" ["issued_date"]=> string(0) "" ["目的"]=> string(0) "" ["notes"]=> string (0) "" }

所以我假设它实际上是一个数组?

然后我还在运行循环之前检查它是否是一个数组。该错误重复了我期望循环运行的次数,因此它似乎是“迭代”。我只是没有得到预期的结果。

我的代码

$titles = $titleBlockLib->search($_POST['document_description']);

      ?>
      <h1>LFFN Data</h1>
        <input type="button" value="Add Row" onclick="titleBlock.addEdit()"/>
        <form onsubmit="titleBlock.search()">
        <label for="search">Search:</label>
          <input id = "search" type="text">
          <input id = "submit" type="submit" value="Search">
        </form>

    <?php
      var_dump($titles);
        if (is_array($titles)) {
            echo "<table class='zebra'>
            <tr><td>Handle</td><td>Description</td><td>Document Number</td><tr>";
            foreach ($titles as $t) {
                printf("<tr><td>%s</td><td>%s<td>%s</td><td class='right'>"
                  . "<input type='button' value='Delete' onclick='titleBlock.del(%u)'>"
                  . "<input type='button' value='Edit' onclick='titleBlock.addEdit(%u)'>"
                  . "</td></tr>", 
                  $t['handle'], $t['document_description'], $t['document_num'],
                  $t['id'], $t['id']
                );
              }
              echo "</table>";
            } else {
              echo "<div>No data found.</div>";
            }
            break;

保险起见--调用我的SQL语句的函数如下-->

function search($document_description){
    $sql = "SELECT * FROM `lffntitleblock` WHERE document_description LIKE '%".$document_description."%'";
    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute();
    $entry = $this->stmt->fetchAll();
    return count($entry)==0 ? false : $entry[0] ;

}

【问题讨论】:

  • 你用什么方法来调试这个问题?
  • - 将 $titles 声明为数组 - 将 $titles 转换为数组 - 对我的 SQL LIKE 语句进行硬编码我已经浏览了代码,var_dumping 每一步以确保它是我所期望的。它一直是。老实说,我真的不知道还能尝试什么,我对 PHP 不是很熟悉,而且是一个新的编码器。你有什么建议吗?
  • 请通过编辑为您的问题添加所有说明

标签: php arrays offset


【解决方案1】:

找到答案了..

我的 sql 语句正在返回..

count($entry)==0 ? false : $entry[0] ;

这是一个布尔值。 删除此语句并返回 $this-&gt;stmt-&gt;fetchAll(); 问题已解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多