修复非法字符串偏移PHP

时间:2015-07-21 18:09:31

标签: php

CODE
Foreach Loop

foreach ($LS::getBase() as $base) {
            $fromDatabaseThumb = $base['base-thumbnail'];
            $fromDatabaseDescription = $base['base-description'];
            $fromDatabaseTitle = $base['base-title'];
        echo " 
        <div style='background-color: #ffffff; width: 725px; height: 280px; display: inline-block; position: relative;''>
        <div style='display: inline-block; max-width: 450px; max-height: 260px; margin: 12px; float: left;' class='baseThumb'>
            <img src='$fromDatabaseThumb' style='max-width: 450px; max-height: 260px'>
        </div>
        <div class='baseInfo' style='display: inline-block; width: 250px; height: 253px; margin-top: 12px;'>
            <h3 style='margin: 0; font-family: helvetica; max-width: 250px; max-height: 22px; overflow: hidden;'>$fromDatabaseTitle</h3>
            <p style='margin-top: 8px; word-wrap: break-word;'>
                <strong>Description:</strong><br>
                " . $fromDatabaseDescription . "
            </p>
        </div>
        </div>
        ";
        }

getBase()功能

public static function getBase($what = '*') {
self::construct();
if( is_array($what) ){
  $columns = implode("`,`", $what);
  $columns  = "`{$columns}`";
}else{
  $columns = $what != "*" ? "`$what`" : "*";
}

$sql = self::$dbh->prepare("SELECT {$columns} FROM baselayouts");
$sql->execute();
$data = $sql->fetch(\PDO::FETCH_ASSOC);
if( !is_array($what) ){
  $data = $what == "*" ? $data : $data[$what];
}
return $data;
}


错误: enter image description here


我的内容

我做过研究,找不到有效的方法。所以我对我的代码进行了修改,但仍然无法修复它。


额外信息

我做了一个var_dump(),因为我在其他帖子中看到了与我所做的var_dump()相同的问题所以我想我会这样做,以防万一会以任何方式帮助你们。

var_dump()

array(4) {
    ["id"]=> string(1) "1"
    ["base-title"]=> string(14) "Base Layout #1"
    ["base-thumbnail"]=> string(24) "/res/img/baseLayout1.png"
    ["base-description"]=> string(73) "This is the base test description. Hopefully it does what it needs to do."
}

1 个答案:

答案 0 :(得分:2)

像这样的foreach循环不会在每次迭代时调用该方法。它在第一个循环中调用一次,然后每个后续迭代循环返回该返回值。因此,调用getBase从查询返回一行,然后从该结果循环遍历每一列,使循环内的$base成为该列中的值,而不是行的数组。 var_dump似乎是从getBase返回的返回值,但不是循环内的$base。如果你在循环中做了var_dump($base);,你会看到每个字符串一次。要解决此问题,您可能希望更改getBase以致电PDOStatement::fetchAll,这将返回像$result[rowNum][colName]这样的二维数组。

编辑:此外,将循环切换到另一个结构,如while循环,将评估每次迭代的完整语句将使您进入无限循环,因为每次调用getBase时,您将重新进行-query,返回第一行并重复。

相关问题