在json输出中使用括号

时间:2017-03-22 06:13:05

标签: php arrays json recursion

以下是我现在的输出: -

{"name":"a","path":"a","type":"folder","items":{"name":"b","path":"a/b","type":"folder","items":{"name":"c.docx","path":"a/b/c.docx","type":"file","size":"20"}}}

我想在项目部分添加括号。所以它就像

{"name":"a", "path":"a", "type":"folder", "items":[{"name":"b", "path":"a/b", "type":"folder", "items":[{"name":"c.docx", "path":"a/b/c.docx", "type":"file", "size":"20"} ] }]}

以下是我使用

的代码
$strings='a/b/c.docx';
$items = explode('/', $strings);
$num = count($items)-1;
$root= array();
$cur = &$root;
$temp = array();
$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'];
   }
}
echo json_encode($root,JSON_UNESCAPED_SLASHES);

我在哪里做错了?
任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我的答案是在数组上工作,我在代码中添加注释来解释它是如何工作的:

<?php
namespace JsonTest;
$strings='a/b/c.docx';

// use namespaced function to avoid polluting global scope
/**
 * @param string $path The path to be processed
 * @return string The JSON structure
 */
function jsonify($path)
{
    // Build file information first in desired format
    $fileInfo = [
        'name' => basename($path), // 'c.docx'
        'path' => $path, // 'a/b/c.docx'
        'type' => 'file', // fixed value
        'size' => '20', // fixed??
    ];

    // Transform ['a', 'b'] to ['a', 'a/b']
    $pathStack = [];
    // Don‘t use result of array_reduce, pass &$pathStack by reference instead
    array_reduce(
        explode(DIRECTORY_SEPARATOR, dirname($path)),  // ['a', 'b']
        function($carry, $dir) use (&$pathStack)  {
            $carry []= $dir;
            $pathStack []= implode(DIRECTORY_SEPARATOR, $carry);
            return $carry;
        }, 
        []
    );

    // Build result from $pathStack and $fileInfo
    $result = array_reduce(
        array_reverse($pathStack), // reverse to begin in nested path
        function($items, $pathHere) {
            return [
                "name" => basename($pathHere), // 1: 'b', 2: 'a'
                "path" => $pathHere, // 1: 'a/b', 2: 'a'
                "type" => 'folder', // fixed
                'items' => [$items], // This is what was missing in the end, wrapping array around items
            ];
        }, 
        $fileInfo // use built $fileInfo for initial $items
    );

    return json_encode($result, JSON_UNESCAPED_SLASHES);
}

echo jsonify($strings);