Omid Omid -4 years ago 148
JSON Question

Use brackets in json output

Here is the output that I have right now:-

{"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"}}}


and I want to add bracket in the items part.So it would be like

{"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"} ] }]}


Here is the code that I'm using

$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);


Where am I doing wrong?

Any help would be appreciated.

Answer Source

My answer‘s working on arrays, I put comments in the code to explain how it works:

<?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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download