将具有url值的PHP数组转换为具有组合值的新数组
我已经尝试了很长时间,但是找不到将数组合并到新数组中的方法. 通常,我迷失在循环和匹配中.;(
I have tried for a long time but couldn't find a way to merge an array in to a new one. Mostly I get lost in looping and matching.;(
我想收到一个可以执行以下操作的php 5方法:
I would like to recieve a php 5 method that can do the following:
示例1
让我们说有一个带有url的数组:
Lets say there is an array with url's like:
Array(
'a',
'a/b/c',
'a/b/c/d/e',
'a/y',
'b/z',
'b/z/q/',
)
网址的每个最后一个文件夹都是用户有权查看的文件夹.
Every last folder of the url's is the folder where a user has the right to view.
我想将数组发送到一个返回新数组的方法,例如:
I would like to send the array to a method that returns a new array like:
Array[](
'a/c/e'
'a/y'
'z/q'
)
该方法将原始数组的某些元素组合为一个元素. 这是因为在允许的结尾文件夹中存在匹配项.
The method has combined some elements of the origninal array into one element. This because there is a match in allowed ending folders.
示例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'
)
我想得到一个像这样的数组:
I would like to get a an array like:
Array[](
'books/book1'
'wall'
'wall'
'projectZ/Bacon'
)
那么最好对原始数组的完整路径进行一些引用(特别是在使用'wall'值的情况下).
Then it would be great (specialy in case of the 'wall' values) to have some references to the full path's of the original array.
请按照以下步骤操作:-
Do it like below:-
<?php
$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);