继续获取未定义的索引错误

时间:2017-08-31 18:05:10

标签: php html

我正在疯狂地解决这个问题。

我在PHP中有这个代码:

 private function searchpage($data) {

  $file = @file_get_contents("./assets/template/search.html");
  $content = "";
  $pages = "";

 foreach ($data as $keys) {
 //var_dump($keys); This gives the correct information,I will show the    
 output later on.

        $content = str_replace("[PHOTO]",$keys['photo'], $file);
        $content = str_replace("[NAME]",$keys['name'], $content);
        $pages .= $content;
  }
 return $pages;
}

来自$ keys的var_dump看起来像这样

  array(1) { [0]=> array(7) { ["_id"]=> string(1) "2" ["_user"]=>    
  string(1) "1" ["_short"]=> string(4) "test" ["_long"]=> string(9)   
  "test long" ["name"]=> string(4) "test" ["_dat"]=> string(10) "2017-  
   08-29" ["photo"]=> string(92) "https://s-media-cache-     
   "}

如您所见,我使用了正确的名称标签。

STR_REPLACE不起作用。我一直收到这个错误:

Undefined index: name in     
/Applications/MAMP/htdocs/test/lib/_layout.php on line 144
Undefined index: photo in /Applications/MAMP/htdocs/test/lib/_layout.php on line 145

奇怪的是:我在不同的HTML页面上做了完全相同的事情,并且它完美地工作。

我不知道这段代码有什么问题。 我确实要求这个功能。我给函数的数据是正确的。它确实打开了正确的HTML页面。唯一不正确的是str_replace。

1 个答案:

答案 0 :(得分:1)

您的$keys表示array拥有$keys[0]['photo']个数据。因此,在PHP中,您可能知道,如果您尝试访问数组变量,则还必须指定索引。

因此,它应该是$keys['photo']而不是$keys[0]['name']。同样,它应该是$keys['name']而不是 $content = str_replace("[PHOTO]",$keys['photo'], $file); $content = str_replace("[NAME]",$keys['name'], $content);

请替换

    $content = str_replace("[PHOTO]",$keys[0]['photo'], $file);
    $content = str_replace("[NAME]",$keys[0]['name'], $content);

{{1}}
相关问题