【发布时间】:2014-07-23 17:10:58
【问题描述】:
我遇到了一个非常棘手的问题...我正在编写一个程序,该程序将从另一个 php 文件中获取数组,对其进行排序并用新数组覆盖 php 文件。我正在对 2 个 php 文件进行一些测试。一个是 index.php,另一个是 PHPPage2.php(那是带有数组的那个)。
这里是代码:PHPPage2.php
<?php
$array = array(
"d" => "lemon",
"a" => "orange",
"b" => "banana",
"c" => "apple"
);
$fruits = array(
"d" => "lemon",
"a" => "orange",
"b" => "banana",
"c" => "apple"
);
?>
这里是 index.php
$NomArray = array();
$lines = array(); #That's an array of lines, it gets all line of the file
$fp = fopen("Test/TextFile.txt", "r");
while (!feof($fp))
{
$line = fgets($fp);
#Lookinf for an "array" variable
for($i = 0; $i < strlen($line); $i++)
{
if($line[$i] == 'a' and $line[$i-1] <> '$' and $line[$i+1] == 'r' and $line[$i+2] == 'r' and $line[$i+3] == 'a' and $line[$i+4] == 'y')
{
$line = trim($line);
$lines[]=$line;
$NomVariable = "";
#looking for the name fo the variable
for($i = 0; $i < strlen($line); $i++)
{
# if there is a $, it's a variable
if($line[$i] == '$')
{
# we take all char until that we hit a "=" or " "
for($j = $i; $j < strlen($line); $j++)
{
if($line[$j] <> '=' and $line[$j] <> ' ')
{
$NomVariable = $NomVariable . $line[$j];
}
else
{
break;
}
}
}
}
#We put the name of the variable in a array
$NomArray[] = $NomVariable;
}
}
}
fclose($fp);
#We include PHPPage2.php
include "Test/PHPPage2.php";
# a for loop to get all variable name HERE IS MY PROBLEM
for($i = 0; $i < count($NomArray); $i++)
{
# I wanna use what is inside $NomArray[$i] as the name of a dynamic variable
$NomVar = $NomArray[$i];
/*
I want to sort the array that as the name of $NomArray[$i],
But I dont know why, when i = 0 ${$NomVar)} is suppose to be equal to $array...
That seems logic to me, but it dosent work...
*/
asort(${$NomVar});
foreach (${$NomVar} as $key => $val)
{
echo "\"$key\" => \"$val\", \n";
}
}
我也看过 http://php.net//manual/en/language.variables.variable.php 但这不起作用:(
提前感谢您的帮助! (对不起,如果我的英语不是最好的)
【问题讨论】:
-
你能描述一下你的代码有什么问题吗?
-
为什么不只是
include第一个文件而不是解析? -
@ForguesR 第一个文件是一个文本文件,他想使用测试文件中的一些值从包含的其他 php 文件中选择要使用的数组。
-
@Machavity,当我调用我的变量变量时,我没有得到任何东西,假设将变量 EXP:${$NomVar)} 的名称更改为 $array 但它似乎没有工作。但是,如果我用 $array 对其进行硬编码,我会在 PHPPage2.php 中得到具有该名称的数组
标签: php arrays variables variable-variables