php - 如何在 foreach 循环中使用 php Heredoc 语法

标签 php heredoc

我在 Controller 中遇到了有关heredoc语法的问题。我的 Controller 功能是这样的:

function active() {
    $userlist = $this->input->post('userlist');
    $userlist = explode(',',$userlist[0]);

    $items = '';

    if( !empty($userlist) ){
        foreach($userlist as $buddy)
        {

            $actv = $this->user_model->check_active_users($buddy);//returns 0 if no results found
            if ( $online_buddies == 0) {
                $items .= <<<EOD
            {
                "fl": "0",
                "fid": "{$buddy}"
            },
EOD;
            }//if returned 0 inactive

        }//foreach
    }//if nt empty $mybuddies

    if ($items != '')
    {
        $items = substr($items, 0, -1);
    }
     header('Content-type: application/json');
?>
{
    "items": [
        <?php echo $items;?>
    ]
}

<?php
        exit(0);

}//end of func active

$userlist 保存user-ids

$this->user_model->check_active_users($buddy) 如果未找到结果,则返回 0。

如果在数据库中找不到结果以及相应的用户 ID,我想获得一个标志 0

但是,

$items .= <<<EOD
{
"fl": "0",
"fid": "{$buddy}"
}
EOD;

此处,fl 返回 0,但 fid 不返回任何内容。我是不是做错了什么 "fid": "{$buddy}"

最佳答案

$html = <<<HTML  //  Set a variable for your dashboard HTML

HTML here...

HTML;  //  This ends the heredoc for now and concludes the HTML to open the PHP back up

//  The follow resumes your pure PHP code
$query = "SELECT * FROM `some_table_in_database`";

$results = mysqli_query($query);


foreach ($results as $record) {

    // Bellow you define the records as variables

    $variable1         = $record->one;
    $variable2         = $record->two;
    // as many variables as you would like

    $html .= <<<HTML //  Now, you have to concatenate to your $html variable (adding on to it) some more HTML

    HTML here....

HTML;  //  Now we need to switch back over to PHP, so we close the HTML for now

    //  Begin more PHP code here for further use down the page

    $html .= <<<HTML  // We open back up the HTML variable to put more HTML in our page

    HTML here...

HTML;  // and this concludes the HTML.  You can keep going on for ever like this alternating between PHP and HTML code in order to get for and foreach loops and such to cooperate.

关于php - 如何在 foreach 循环中使用 php Heredoc 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24217241/

相关文章:

node.js - 使用 --input-type 时无法加载本地目录 Node.js 模块

php - 设计一种不同类型的标签云

php - 内容长度 header 设置不正确

php - Eclipse Kepler - PHP 代码完成不工作

ruby - vagrant vm 中的 bash heredoc 提供了heredoc

linux - 使用shell脚本创建shell脚本

javascript - 用于在 JavaScript 中捕获 Heredoc 的正则表达式

php - 尝试验证名称字段以确保它全部是字母字符或连字符或撇号

php - 在后台执行 Laravel/Symfony/Artisan 命令

ruby - 如何从 Ruby HEREDOC 中删除前导空白字符?