我无法将文件中的值插入到php关联数组中。有人可以帮忙吗? 代码如下,查看第3个数组项,我想从文件中插入键值,但每次出错都是如此。怎么做? (包含,回显或函数结果 - 在数组内部不起作用!)。怎么做?
<?
$somedeclaredvaiable = '0 => "value1", 1 => "value2", 2 => value3", 3 => "value4", 4 => "value5", 7 => 4';
$a = array(
1 => array(
0 => "value1",
1 => "value2",
2 => "value3",
3 => "value4",
4 => "value5",
7 => 4
),
2 => array(
0 => "value1a",
1 => "value2a",
2 => "value3a",
3 => "value4a",
4 => "value5a",
7 => 4
),
3 => array(
//THE PROBLEM IS HERE, can't include file, or echo an variable!
include 'filewitharray.txt'; //doesn't work
echo $somedeclaredvariable ; //doesn't work
),
);
?>
答案 0 :(得分:1)
这段代码在语法上是不正确的:
3 => array(
//THE PROBLEM IS HERE, can't include file, or echo an variable!
include 'filewitharray.txt'; //doesn't work
echo $somedeclaredvariable ; //doesn't work
),
假设filewitharray.txt
是一个将返回数组(或其他内容)的php文件,如下所示:
<?php
return array('foo' => 'bar');
然后,你可以这样做:
$a[] = require 'filewitharray.txt';
它会将filewitharray.txt
返回的变量添加到您的表格中。
如果filewitharray.txt
不应该是PHP代码,并且您希望将文件的内容添加到数组中(作为字符串),那么您可以这样做:
<?php
$a[] = file_get_contents('filewitharray.txt');
答案 1 :(得分:0)
立即尝试。
<?php
include 'filewitharray.txt';
$somedeclaredvaiable = '0 => "value1", 1 => "value2", 2 => value3", 3 => "value4", 4 => "value5", 7 => 4';
$a = array(
1 => array(
0 => "value1",
1 => "value2",
2 => "value3",
3 => "value4",
4 => "value5",
7 => 4
),
2 => array(
0 => "value1a",
1 => "value2a",
2 => "value3a",
3 => "value4a",
4 => "value5a",
7 => 4
),
3 => array(
),
);
?>
答案 2 :(得分:0)
首先,事先获取文件的内容:
$included = file_get_contents("file with array.txt");
然后在你的数组声明中:
...snip
3 => array(
$included, $somedeclaredvariable
)
);