douwo5710 2015-02-04 23:27
浏览 20
已采纳

Foreach语句打印出不正确的格式

First of all I have a array stored in the variable $magazine_issue_pages that if you print the array shows the following.

Array ( [0] => http://104.131.209.93/wp-content/uploads/2015/02/1.jpg [1] => http://104.131.209.93/wp-content/uploads/2015/02/2.jpg [2] => http://104.131.209.93/wp-content/uploads/2015/02/3.jpg [3] => http://104.131.209.93/wp-content/uploads/2015/02/4.jpg [4] => http://104.131.209.93/wp-content/uploads/2015/02/back.jpg ) 1

So the variable definitly is storing the array properly. However when I go to put it in my foreach statement it is incorrect.

Here is my PHP foreach statement

foreach ($magazine_issue_pages as $magazine_issue_page) {
    echo '<div style="background:url('.$magazine_issue_page.')"';
}

It is printing the following in HTML

<div div="" <="" <div="" style="background:url(http://104.131.209.93/wp-content/uploads/2015/02/1.jpg)"></div>

Obviously this isn't what I am looking for ha...

Looking more for something like this

    <div style='background:url("http://104.131.209.93/wp-content/uploads/2015/02/1.jpg")'></div>
    <div style='background:url("http://104.131.209.93/wp-content/uploads/2015/02/2.jpg")'></div>
    <div style='background:url("http://104.131.209.93/wp-content/uploads/2015/02/3.jpg")'></div>
    <div style='background:url("http://104.131.209.93/wp-content/uploads/2015/02/4.jpg")'></div>
    <div style='background:url("http://104.131.209.93/wp-content/uploads/2015/02/back.jpg")'></div>

Also on a side note when I am writing my echo in my foreach statement I am slightly overwhelmed. As I need to have the url surrounded in " or ' however I already have both of those used in the echo statement so how am I supposed to surround it?

Huge thanks in advance!

  • 写回答

2条回答 默认 最新

  • dpmrakfbx820320638 2015-02-04 23:33
    关注

    Well, you do miss a bit of the mark-up in your echo? This should do the trick:

    foreach ($magazine_issue_pages as $magazine_issue_page) {
        echo '    <div style="background:url(\'' . $magazine_issue_page . '\')"></div>' . PHP_EOL;
    }
    

    Another way of doing it, that may make it easier to spot what's missing, is to use a template, like this:

    $template = '    <div style="background:url(\'{{url}}\')"></div>';
    foreach ($magazine_issue_pages as $magazine_issue_page) {
        echo str_replace('{{url}}', $magazine_issue_page, $template) . PHP_EOL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP