我已经尝试了很长时间,但是找不到将数组合并到新数组中的方法.
通常,我迷失在循环和匹配中.
我想接收可以执行以下操作的php 5方法:
例子1
可以说有一个带有url的数组:
Array(
'a',
'a/b/c',
'a/b/c/d/e',
'a/y',
'b/z',
'b/z/q/',
)
url的每个最后一个文件夹是用户有权查看的文件夹.
我想将数组发送到一个返回新数组的方法,例如:
Array[](
'a/c/e'
'a/y'
'z/q'
)
该方法将原始数组的某些元素组合为一个元素.
这是因为在允许的结尾文件夹中存在匹配项.
例子2
Array(
'projects/projectA/books'
'projects/projectA/books/cooking/book1'
'projects/projectA/walls/wall'
'projects/projectX/walls/wall'
'projects/projectZ/'
'projects/projectZ/Wood/Cheese/Bacon'
)
我想要一个像这样的数组:
Array[](
'books/book1'
'wall'
'wall'
'projectZ/Bacon'
)
然后,最好对原始数组的完整路径进行一些引用(特别是在“壁”值的情况下).
解决方法:
像下面这样:
$array = Array(
'projects/projectA/books',
'projects/projectA/books/cooking/book1',
'projects/projectA/walls/wall',
'projects/projectX/walls/wall',
'projects/projectZ/',
'projects/projectZ/Wood/Cheese/Bacon'
);// original array
$final_array =array(); // new array variable
foreach($array as $key=>$arr){ // iterate over original array
$exploded_string = end(array_filter(explode('/',$arr))); // get last-value from the url string
foreach($array as $ar){ // iterate again the original array to compare this string withh each array element
$new_exploded_string = end(array_filter(explode('/',$ar))); // get the new-last-values from url string again
if($arr !== $ar && strpos($ar,$exploded_string) !==false){ // if both old and new url strings are not equal and old-last-value find into url string
if($exploded_string == $new_exploded_string ){ // if both new-last-value and old-last-value are equal
$final_array[] = $exploded_string;
}else{
$final_array[] = $exploded_string.'/'.$new_exploded_string ;
}
}
}
}
print_r($final_array);
标签:php,arrays
来源: https://codeday.me/bug/20191013/1909624.html