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条)

报告相同问题?

悬赏问题

  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开