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

时间:2014-06-14 06:27:18

标签: php heredoc

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

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

2 个答案:

答案 0 :(得分:2)

$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.

答案 1 :(得分:1)

对于您正在创建的内容,heredoc似乎有点多了。那么为什么不这样做呢:

$items .= '{
           "fl": "0",
           "fid": "' . $buddy . '"
           },'