doujia8801 2017-08-31 18:05
浏览 42
已采纳

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

I am literarily driving myself nuts with this problem.

I have this code in 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;
}

The var_dump from $keys looks like this

  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-     
   "}

as you can see, I use the correct name tags.

The STR_REPLACE doesn't work though. I keep getting this error:

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

The strange thing is: I do EXACTLY the same thing on a different HTML page, and there it works perfectly.

I have no clue what's wrong with this code. I do request the function. The data I give to the function is correct. It does open the correct HTML page. The only thing which isn't correct is the str_replace.

  • 写回答

1条回答 默认 最新

  • dongsu1951 2017-08-31 18:16
    关注

    Your var_dump says that $keys holds an array of data. Thus, in PHP, as you may know, if you are trying to access an array variable, you must specify the index also.

    Thus, it should be $keys[0]['photo'] instead of $keys['photo']. Similarly, it should be $keys[0]['name'] instead of $keys['name'].

    Please replace

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

    with

        $content = str_replace("[PHOTO]",$keys[0]['photo'], $file);
        $content = str_replace("[NAME]",$keys[0]['name'], $content);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用