将字符串转换为嵌套数组php

时间:2017-03-20 15:02:05

标签: php arrays foreach

我正在尝试将字符串转换为嵌套数组 这是我的字符串:

a/b/d.docx

我希望如此:

array(
    "name" => "a",
    "type" => "folder",
    "sub" => array(
        "name" => "b",
        "type" => "folder",
        "sub" => array(
            "name" => "c.docx",
            "type" => "file",
            "size" => "20"
        )
    )
)

这是我到目前为止的代码

$items = explode('/', $strings);
$num = count($items);
$num = --$num; 
$temp = array();
foreach($items as $keys => $value) {
    $temp[$keys] = array(
        "name" => $value,
        "type" => "folder",
        "items" => $temp[++$keys]
    );
    if($keys == $num){
        $temp[$keys] = array(
            "name" => $value,
            "type" => "file",
            "size" => "20"
        ); 
    }
}
var_dump($temp);

我正在尝试此功能,但这只是将字符串转换为单个数组,而且它也无法执行“'项目'行。
任何帮助将不胜感激。谢谢 请注意,路径是虚拟的,并不存在 更新:如何添加每个数组的路径?例如,"path"=>"a/b"

3 个答案:

答案 0 :(得分:2)

你可以这样做:

$path = 'a/b/d.docx';

$parts = explode('/', $path);

$result = [ 'name' => array_pop($parts), 'type' => 'file', 'size' => 20 ];

while ($parts) {
    $result = [ 'name' => array_pop($parts), 'type' => 'folder', 'sub' => $result ];
}

print_r($result);

答案 1 :(得分:0)

尝试递归:

Optimization completed: The first-order optimality measure, 3.114006e-10,
is less than options.OptimalityTolerance = 1.000000e-06.

Optimization Metric                                       Options
relative first-order optimality =   3.11e-10  OptimalityTolerance =   1e-06 (default)

答案 2 :(得分:0)

<?php
$strings='a/b/d.docx';

$items = explode('/', $strings);
$num = count($items)-1;

$root= array();
$cur = &$root;

$v='';

foreach($items as $keys => $value) {

    $v = $v.$value;
    $temp = array(   "name" => $value,  "path"=>$v,  "type" => "folder",    "items" => "");
    if($keys == $num){ 
        $temp = array( "name" => $value, "path"=>$v, "type" => "file", "size" => "20"); 
    }
    $v= $v.'/';

    if($keys==0) {
        $cur = $temp;
    }
    else
    {
        $cur['items'] = $temp;      
        $cur = &$cur['items'];
    }
}
var_dump($root);