【问题标题】:include if value in array defined on included file包含如果在包含文件上定义的数组中的值
【发布时间】:2015-07-20 21:43:53
【问题描述】:

我想检查页面名称是否是包含文件中定义的数组中的值,如果是,则包含它。

<?php

// parent page that includes the files

$pageLabel = 'three';

if (in_array('pageLabel', $multicats)) {
    include $filename;
}

?>


<?php

// example for a file to be included

$multicats = array('one', 'three', 'five');
$filename = $_SERVER['PHP_SELF'];

echo 'Hello World of one, three and five';

?>

然而,一个错误表明它期望 $multicats 是一个数组,它确实是一个数组,这意味着它不会检查包含的文件。

怎么办?

【问题讨论】:

  • 你为什么要这样做?检查一个值是否在一个文件中的数组中没有多大意义,如果该值在数组中,您只想包含该文件
  • 您是否包括在 中定义了数组的文件?
  • 是的!目录中的每个文件都有一个数组。如果该数组中的某个值与父页面上定义的变量匹配,则应将其包含在内。

标签: php arrays include


【解决方案1】:

在条件之前,您必须在父页面中的某处拥有多猫数组。如果你在包含的文件中有它,它会在使用条件后初始化。或者您可以使用 isset 检查它是否存在,就像 Crunch 船长所说的那样。

注意:在in_array 条件下,你有字符串'pageLabel' 而不是var $pageLabel,对吗?

【讨论】:

    【解决方案2】:

    首先,您应该传递:$pageLabel var,而不是 'pageLabel' 字符串(参见代码中的第 4 行)。

    其次,我建议你使用“isset”:

    if ( isset($multicats) && isset($multicats[$pageLabel]) && isset($filename) ) 
        include $filename;
    

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 2012-02-13
      • 2013-01-07
      相关资源
      最近更新 更多