首页 > 解决方案 > 当包含多个文件时,返回一个数组,我将第一个包含的数组合并到第二个包含中,为什么?

问题描述

我有很多 .php 文件,它们都应该返回一个不同键和值的数组,我想将每个 .php 文件包含在一个大的多维数组中,返回对应的数组,如下所示:

$array
    'file1.php' = ['something' => 'someValue'],
    'file2.php' = ['somethingElse' => 'someValue']

我通过制作一个 foreach .php 文件并将该文件包含到 $array[$filename] 中来做到这一点,但是 file2.php 数组与 file1.php 合并,所以我得到的是:

$array
    'file1.php' = ['something' => 'someValue'],
    'file2.php' = ['something' => 'someValue', 'somethingElse' => 'someValue']

我不明白为什么?这是我的示例代码:

文件1.php:

$array = ['something' => 'someValue'];
return $array;

文件2.php

$array = ['somethingElse' => 'someValue'];
    return $array;

测试.php

$array[1] = include_once "/var/www/html/folder/file1.php";
$array[2] = include_once "/var/www/html/folder/file2.php";
print_r($array);

输出是:

$array
    1 = ['something' => 'someValue'],
    2 = ['something' => 'someValue', 'somethingElse' => 'someValue']

和预期的输出:

$array
    1 = ['something' => 'someValue'],
    2 = ['somethingElse' => 'someValue']

我怎样才能存档这个输出呢?我的代码有什么问题?

标签: phparrays

解决方案


尝试做这样的事情:

文件*.php:

return ['something' => 'someValue'];

说明:包含重写 $array 变量。

你也可以使用这个:

function get_include_array($filename) {
return include_once"/var/www/html/folder/$filename";
}

因为函数使用非全局变量


推荐阅读