【问题标题】:Check if exist in array (all in foreach)检查数组中是否存在(都在foreach中)
【发布时间】:2015-12-11 20:47:36
【问题描述】:

我需要检查另一个数组中的每一行,如果存在 - 做点什么。

这是我的代码:

<?php $Sekcje = explode( ',', $Detail->SectionsPrefered ); ?>
     <?php foreach ($SectionsList as $SectionOption): ?>
           <div class="checkbox">
           <?php if ( in_array( $SectionOption->Title , $Sekcje ) ): ?>
                 *
           <?php endif ?>
               <label>
                  <input type="checkbox" value="<?php echo $SectionOption->Title; ?>">
                  <?php echo $SectionOption->Title; ?>
               </label>
           </div>
     <?php endforeach ?>

它只显示一个'*',但必须显示3行(Section1,Section2,Section3)

这里是 var_dumps:

$Sekcje

array(3) {
  [0]=>
  string(8) "Section1"
  [1]=>
  string(9) " Section2"
  [2]=>
  string(9) " Section3"
} 

$SectionsList

array(5) {
  [0]=>
  object(stdClass)#33 (3) {
    ["ID"]=>
    string(1) "1"
    ["Title"]=>
    string(8) "Section1"
    ["Description"]=>
    string(13) "Opis sekcji 1"
  }
  [1]=>
  object(stdClass)#34 (3) {
    ["ID"]=>
    string(1) "2"
    ["Title"]=>
    string(8) "Section2"
    ["Description"]=>
    string(13) "Opis sekcji 2"
  }
  [2]=>
  object(stdClass)#35 (3) {
    ["ID"]=>
    string(1) "3"
    ["Title"]=>
    string(8) "Section3"
    ["Description"]=>
    string(13) "Opis sekcji 3"
  }
  [3]=>
  object(stdClass)#36 (3) {
    ["ID"]=>
    string(1) "4"
    ["Title"]=>
    string(8) "Section4"
    ["Description"]=>
    string(13) "Opis sekcji 4"
  }
  [4]=>
  object(stdClass)#37 (3) {
    ["ID"]=>
    string(1) "5"
    ["Title"]=>
    string(8) "Section5"
    ["Description"]=>
    string(13) "Opis sekcji 5"
  }
} 

【问题讨论】:

标签: php arrays codeigniter foreach


【解决方案1】:

in_array() 确实(ish)字符串匹配,并且您的字符串不同。来自您自己的转储:

string(9) " Section2"
string(8) "Section2"

注意$Sekcje 中的多余空间

【讨论】:

    【解决方案2】:

    正如 MarcB 所指出的,您的值中有空格是由 explode() 引起的。不要使用explode(),而是使用:

    preg_split('/\s*,\s*/', $Detail->SectionsPrefered, -1, PREG_SPLIT_NO_EMPTY)
    

    这将避免数组值周围有空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 2011-06-20
      • 2020-07-06
      相关资源
      最近更新 更多