【问题标题】:Include a php-file with multiple arrays [closed]包含具有多个数组的 php 文件 [关闭]
【发布时间】:2017-07-07 06:01:56
【问题描述】:

我在使用简单的 include 语句时遇到了问题,我不知道是什么原因造成的。

首先,我将有关表和列的信息存储在一个名为 dbInit.php 的文件中

看起来像这样:

<?php

   $aTableNames = array (
   "tbl_crs" => "tbl_crs",
   "tbl_lct" => "tbl_lct",
   "tbl_prf" => "tbl_prf",
   "tbl_qst" => "tbl_qst",
   "tbl_uni" => "tbl_uni",
   "tbl_usr" => "tbl_usr"
   );

   $aAuxTableNames = array (
   "aux_crs_lct" => "aux_crs_lct",
   "aux_lct_prf" => "aux_lct_prf",
   "aux_uni_crs" => "aux_uni_crs"
   );

?>

现在我只想从另一个文件访问这些数组。所以我把它包括在内:

include "Ini/dbInit.php";

到目前为止一切顺利。现在我想像这样使用数组的值:

$sTable1 = $aAuxTableNames["aux_uni_crs"];
$sTable2 = $aTableNames["tbl_crs"];

目录如下所示:

我怎样才能以上面播种的方式访问这些数组?

非常感谢。

最好的问候 安尼

【问题讨论】:

  • 我不知道你到底在问什么
  • error_reporting(E_ALL); ini_set('display_errors', '1');
  • 我想让我的代码尽可能地全球化。所以我想将几乎所有信息都存储在外部文件中。就像文件 dbIni.php 一样。这样我就可以在这个包含文件中更改它一次,它是整个代码中的更改。但由于某种原因,我根本无法访问这些数组。
  • 您是否收到错误消息?您的主脚本是否能够找到包含的文件?如果您按照 AbraCadaver 的建议设置了错误报告,请尝试在包含的文件中添加 echo 语句,以确认它被包含在内。
  • 你已经告诉我们你做了什么,但你没有告诉我们两个关键信息:(1) 发生了什么? (2) 你预计会发生什么?

标签: php arrays include


【解决方案1】:

我没有问题实现这一点。所以基本上这就是我所做的。我通过包含数组的包含文件复制了您的结构,正如您在此处发布的那样。然后我在服务器的根目录上创建了一个测试文件。这个测试文件也是 php,我照常进行了包含。创建了新变量,然后 print_r('');您创建的 2 个新变量没有收到任何错误。

这是我的 dbinit.php 文件:

 <?php 
     $aTableNames = array (
     "tbl_crs" => "tbl_crs",
     "tbl_lct" => "tbl_lct",
     "tbl_prf" => "tbl_prf",
     "tbl_qst" => "tbl_qst",
     "tbl_uni" => "tbl_uni",
     "tbl_usr" => "tbl_usr"
     );

    $aAuxTableNames = array (
    "aux_crs_lct" => "aux_crs_lct",
    "aux_lct_prf" => "aux_lct_prf",
    "aux_uni_crs" => "aux_uni_crs"
    );
?>

好的,和你的完全一样。然后我在名为 testpage.php 的根目录上创建了我的文件:

<?php

include('inc/dbinit.php');

$sTable1 = $aAuxTableNames["aux_uni_crs"];
$sTable2 = $aTableNames["tbl_crs"];

print_r($sTable1);
print_r($sTable2);


?>

我的结构如图所示:Structure

运行此程序或检索数据绝对没有问题。希望这会有所帮助。

最终输出:Final Output

【讨论】:

  • 感谢您的测试。我刚刚删除了文件并重新创建了它,由于某种原因,即使我没有改变任何东西,它也能正常工作。
  • 当然,很高兴你能弄明白!我没有看到任何错误,这就是我使用 print_r(); 的原因。看看结果如何。祝你好运!
【解决方案2】:

试试这个:

// Ini/dbInit.php
<?php

return array(
    'aTableNames' => array(
        "tbl_crs" => "tbl_crs",
        "tbl_lct" => "tbl_lct",
        "tbl_prf" => "tbl_prf",
        "tbl_qst" => "tbl_qst",
        "tbl_uni" => "tbl_uni",
        "tbl_usr" => "tbl_usr"
    ),

   'aAuxTableNames' => array(
        "aux_crs_lct" => "aux_crs_lct",
        "aux_lct_prf" => "aux_lct_prf",
        "aux_uni_crs" => "aux_uni_crs"
    ),
);

在文件中,您想要获取 Ini/dbInit.php

<?php

$config = include "Ini/dbInit.php";
$sTable1 = $config['aAuxTableNames']['aux_uni_crs']
$sTable2 = $config['aTableNames']['tbl_crs'];

【讨论】:

  • 我刚试过你的代码,它工作得很好。但由于某种原因,我的现在也在工作。非常感谢:)
猜你喜欢
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 2022-10-22
相关资源
最近更新 更多