在数组中添加与php中的uri相关的字符串
无法确定如何在数组中特定位置插入关于给定uri的新字符串 更具体地说, 我正在尝试创建一个如下函数:在数组中添加与php中的uri相关的字符串,php,eval,Php,Eval,无法确定如何在数组中特定位置插入关于给定uri的新字符串 更具体地说, 我正在尝试创建一个如下函数: function insertNewFolder($name, $path){ $struct = json_decode( file_get_contents('structure.json'), true ); //at this place I want to include $name in the array according the given $path } 假设$
function insertNewFolder($name, $path){
$struct = json_decode( file_get_contents('structure.json'), true );
//at this place I want to include $name in the array according the given $path
}
假设$struct是以下数组:
$struct = array( 'folder' => array('subfolder1', 'subfolder2') );
注意:范围可以是多个子文件夹。
示例:array('folder'=>array('subfolder'=>array('subsubfolder'))代码>
如果我像这样调用方法insertNewFolder('subfolder3','folder')代码>生成的数组应为:
$struct = array( 'folder' => array('subfolder1', 'subfolder2', 'subfolder3') );
这是我的尝试:
function insertNewFolder($name, $path){
...
// insert the new folder according the path
$segments = explode('/', $path);
$arr_path = '';
foreach( $segments as $s ){
$arr_path .= "['$s']";
}
eval("/$menu$arr_path[] = '$name';");
...
}
如果eval方法没有引发异常,这将起作用:
Parse error: syntax error, unexpected ']', expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 16
我请求你的帮助,有没有更好的方法达到这个目的,或者如何绕过这个例外
关于我不太确定您想要什么,但为了得到您想要的结果,为什么不使用:
function insertNewFolder($name, $path){
$struct[$name][]=$path;
}
除此之外,尽量避免eval()。在99.99%的情况下,您可以不使用
如果您有一个多维数组,例如:
$segments = explode('/', $path);
$arr_path = '';
$tmp_struct=&$struct;
for ($i=0;$i<(count($segments)-1);$i++) {
if (!isset($tmp_struct[$segments[$i]]) {
$tmp_struct[$segments[$i]]=1;
}
$tmp_struct=$tmp_struct[$segments[$i]];
}
$tmp_struct[$segments[count($segments)-1]]=$name;
$segments=分解(“/”,$path);
$arr_path='';
$tmp_struct=&$struct;
对于($i=0;$i您可以执行类似()的操作:
您的复合数据结构没有规范化,这使得您的问题很难解决
请参见您给出的第一个示例:
array( 'folder' => array('subfolder1', 'subfolder2') );
文件夹是文件夹
的数组键,但子文件夹名称是数组值
您的第二个示例更清楚地说明了这一点:
array( 'folder' => array( 'subfolder' => array( 'subsubfolder' )));
现在,您在使用insert操作处理每个可能的情况时遇到了问题,但您没有在问题中写入如何处理不同的情况,例如,您想在何处插入什么以及如何将path
映射到数组键或值
<>你应该考虑改写你的问题,添加丢失的信息,使用更简单的语言和更好的例子。如果有帮助的话,画一张图片。你能用EVE语句解释你想要完成什么吗?抱歉可能会有点混乱,但是如果你读得好,你应该明白我想完成什么。它可以是结构中的多个子文件夹。通常情况下(这是一句谚语):“如果eval()是答案,你几乎肯定问错了问题”——如果它们是结构中的多个子文件夹呢?比如数组('folder'=>array('subfolder'=>array('subsubfolder1'))
array( 'folder' => array( 'subfolder' => array( 'subsubfolder' )));