我在 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/