将具有url值的PHP数组转换为具有组合值的新数组 [英] PHP array with url values to new array with combined values

查看:74
本文介绍了将具有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);

输出:- https://eval.in/846738

这篇关于将具有url值的PHP数组转换为具有组合值的新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆