简体   繁体   English

php if语句在foreach循环中的问题

[英]issues with php if statement within foreach loop

I did have a quick search on this but couldn't find anything relating to my problem. 我确实对此进行了快速搜索,但是找不到与我的问题有关的任何内容。 I'm having issues with an if statement within a foreach loop. 我在foreach循环中的if语句遇到问题。 I'm pulling a list of categories from one class, and a single category to be selected from another. 我从一个类别中提取类别列表,并从另一个类别中选择一个类别。 The code below (with the if statement removed) works perfectly, and returns 12 options with populated values. 下面的代码(除去了if语句)可以正常工作,并返回12个带有填充值的选项。

foreach ($user_info->categories as $key=>$category) {
    $category_name = $user_info->category_names[$key];
    echo '<option value="'.$category.'">'.$category_name.'</option>';
}

However when I add the if statement inside as below: 但是,当我在其中添加if语句时,如下所示:

foreach ($user_info->categories as $key=>$category) {
    $category_name = $user_info->category_names[$key];
    if ($category = $get_article_info->category_1) {
        echo '<option value="'.$category.'" selected="selected">'.$category_name.'</option>';
    } else {
        echo '<option value="'.$category.'">'.$category_name.'</option>';
    }
}

I get a list of options with the text populated but all twelve options have value="". 我得到一个填充了文本的选项列表,但所有十二个选项的值都为value =“”。 $get_article_info->category_1 works when echoed on it's own, and even if it were not found I would expect the if statement to echo 12 options without any selected (the same as the first code example). $ get_article_info-> category_1可以在其自身被回显时工作,即使找不到它,我也希望if语句回显12个未选择任何选项的选项(与第一个代码示例相同)。

You are using = instead of == You should change 您正在使用=而不是==您应该进行更改

 if ($category = $get_article_info->category_1) {

To

  if ($category == $get_article_info->category_1) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM