如何从PHP中的关联数组创建嵌套Json数组

时间:2019-07-11 09:27:54

标签: php arrays json

我正在设置文件浏览器,但想解析JSON数组以获取文件夹层次结构,但无法从关联数组中创建所需的JSON数组结构。

这是我从数据库中获取的两个关联数组。

$directory  = Array ( [0] => stdClass Object ( [dir_name] => Car [dir_id] => car ) [1] => stdClass Object ( [dir_name] => Bus [dir_id] => bus ) )

$subdirectory = Array ( [0] => stdClass Object ( [sub_name] => Toyota [sub_id] => toyota [dir_id] => car) [1] => stdClass Object ( [sub_name] => Volvo [sub_id] => volvo [dir_id] => bus) )

我被这样尝试

$parentdirectory = [];
$parentfolder = [];
$subf = [];
$subfolder = [];

foreach ($directory  as $dir) {
  $parentdirectory['id'] = $dir->id;
  $parentdirectory['value'] = $dir->name;
  foreach (subdirectory as $sub) {
    if ($dir->dir_id == $sub->dir_id) {
      $subfolder['id'] = $sub->sub_id;
      $subfolder['value'] = $sub->sub_name;
      array_push($subf, $subfolder);
      array_push($parentdirectory, $subf);
    }
  }
  array_push($parentfolder, $parentdirectory);
}

echo json_encode($parentfolder);

实际上,我想要这样的JSON数组

[
    {
        id: "car",
        value: "Car",
        data: [{
            id: "toyota",
            value: "Toyota"
        }]
    },
    {
        id: "bus",
        value: "Bus",
        data: [{
            id: "volvo",
            value: "Volvo"
        }]
    }
]

2 个答案:

答案 0 :(得分:1)

您在foreach循环内的foreach循环效率低下。首先循环遍历$子目录来创建数据数组,然后遍历$目录以获取实际格式。

$dataArray = array();
$parentfolder = array();

foreach( $subdirectory as $sub ) {
    $dirName = $sub->dir_id;
    if( !isset( $dataArray[$dirName] ) ) {
        $dataArray[$dirName] = array();
    }
    $dataArray[$dirName][] = array('id' => $sub->sub_id, 'value' => $sub->sub_name);
}

foreach ($directory  as $dir ) {
    $dirName = $dir->dir_id;
    if( isset ( $dataArray[$dirName] ) ) {
        $data = $dataArray[$dirName];
    } else {
        $data = array();
    }
    $parentfolder[] = array('id' => $dir->dir_id, 'value' => $dir->dir_name, 'data' => $data);
}

echo json_encode($parentfolder);

答案 1 :(得分:0)

我认为您应该首先将lapply(1:length(start), function(x) subcomponent(g, V(g)$name == start[x], "out")) 设置为data,如下所示:

array