dongmeixian9665 2014-07-31 11:25
浏览 76

如何将DirectoryIterator中的数组转换为有效的Json格式

For testing purpose, i am Looking to convert an array into a valid Json format. To do this, I get a list of files from a directory. This gives me as result:

{"data":["file1.txt","file2.txt","file3.txt"]}

Here's my code:

public function getDirectories() {
    $dir = $this->getConfig(); // My Directory
    $array = array();
    $handle = opendir($dir);
    while (FALSE !== ($entry = readdir($handle))) {
        if ($entry == '.' || $entry == '..')
            continue;
        $array[] = $entry;
    }
    return $array;
}

And My class for processing:

class ArrayValue implements JsonSerializable {

    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return array('data' => $this->array);
    }
}

I think I have a here a json result format certainly, but this appears to be invalid, since I have an array in the json. So How do I proceed to get the following format like this?

{"data":{"file1.txt","file2.txt","file3.txt"}}
  • 写回答

1条回答 默认 最新

  • dpbv85276 2014-07-31 11:34
    关注

    You first JSON string is fine, since keys of files are numeric, so it's array, and not object.
    To simplify everything, you can collect everything to array

    $data = [
       [
           'data' => [
               'file1.txt',
           ],
           [
               'file2.txt',
           ],
    
           [
               'file3.txt',
           ],
       ]
    ];
    

    And than just convert array to JSON:

    $json = json_encode($data);  // will return valid json
    $array = json_decode($json); // will return parsed json
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条