douzhiba6873 2017-11-13 18:01
浏览 48
已采纳

PHP函数创建div,称为x次

I am attempting to make an html element that contains x amount of other divs created by a function where x is dependent on the number of elements $allposts contains.

<div id="postings">
    <?php
    foreach($allposts as $key => $value){
        createPost($key, $value);
    }
    ?>
 </div>

This html and php code above is my attempt to create a "posting" for each item that is found in the $allposts array.

<?php
    function createPost($author, $input)
    {
        $data = [];
        $i = 0;
        foreach($input as $key => $value){
            $data[$i] = $value;
            $i++;
        }
        echo "<div>
                <span class='post-title'>$data[0]</span>
                <span class='post-author'>$author</span>
                <span class='post-date'>$data[1]</span>
                <p class='post-desc'>$data[2]</span>
            </div>";
     }
?>

This is the php document that contains the function createPost($author, $input).

The function works but it seems that each time the function is being called, the previous post is overridden leaving only one post visible which ends up being the last one in the array.

  • 写回答

2条回答 默认 最新

  • doucheng5705 2017-11-13 18:08
    关注

    Get the $data array declaration outside of foreach and the other change needs to be done is, do not use $i as key of $data array because everytime, it will be declared with 0 (zero) and so, all new values replace the previos one. So instead of using $i keep it $data[] so it will automatically add numeric indexes.

    <?php
        $data = [];    // I took it out of the loop.
        function createPost($author, $input)
        {
            foreach($input as $key => $value){
            $data[] = $value;
        }
        echo "<div>
                    <span class='post-title'>$data[0]</span>
                    <span class='post-author'>$author</span>
                    <span class='post-date'>$data[1]</span>
                    <p class='post-desc'>$data[2]</span>
               </div>";
         }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计