如何将PHP数组转换为JS嵌套对象数组

时间:2019-06-26 11:43:46

标签: javascript php

用于呈现 Tree-View 的特定jQuery插件期望“嵌套对象数组” 的数据字符串。我的Tree-View数据(具有相同的结构)在PHP数组中可用。我需要以jQuery插件可以读取数据的方式来回显PHP数组。

我已经尝试过 json_encode PHP数组,但是得到的结果与jQuery插件的预期完全不同。期望/要求的数据格式可以在这里查看: https://mbraak.github.io/jqTree/#options-data 以及以下:

var data = [
    {
        name: 'node1',
        children: [
            { name: 'child1' },
            { name: 'child2' }
        ]
    },
    {
        name: 'node2',
        children: [
            { name: 'child3' }
        ]
    }
];

我需要转换为上述JavaScript格式的PHP数组(但是,这只是一个示例):

Array
(
    [1] => Array
        (
            [name] => CEO
            [id] => 1
            [children] => Array
                (
                    [3] => Array
                        (
                            [name] => Director 1
                            [id] => 3
                            [children] => Array
                                (
                                    [4] => Array
                                        (
                                            [name] => Senior Manager 1
                                            [id] => 4
                                            [children] => Array
                                                (
                                                    [5] => Array
                                                        (
                                                            [name] => Manager 1
                                                            [id] => 5
                                                            [children] => Array
                                                                (
                                                                )
                                                        )
                                                )
                                        )
                                )
                        )
                    [6] => Array
                        (
                            [name] => Director 2
                            [id] => 6
                            [children] => Array
                                (
                                    [7] => Array
                                        (
                                            [name] => Senior Manager 2
                                            [id] => 7
                                            [children] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )
)

编辑:

这是我生成数组的方式:

$objectTempRoles = $this->roleRepository->findAll();
    $aTempRoles = [];
    foreach($objectTempRoles as $oRole){
        if($oRole->getIsroot() == 1){
            $aTempRoles[$oRole->getUid()] = [];
            $aTempRoles[$oRole->getUid()]['name'] = $oRole->getTitle();
            $aTempRoles[$oRole->getUid()]['id'] = $oRole->getUid();
            $aTempRoles[$oRole->getUid()]['children'] = $this->functionGetChildren($oRole);
        }
}


public function functionGetChildren($oRole){
    $aChildrenToReturn = [];
    if($oRole->getChildren() != null && $oRole->getChildren() != false){
        foreach($oRole->getChildren() as $oChild){
            $aChildrenToReturn[$oChild->getUid()] = [];
            $aChildrenToReturn[$oChild->getUid()]['name'] = $oChild->getTitle();
            $aChildrenToReturn[$oChild->getUid()]['id'] = $oChild->getUid();
            $aChildrenToReturn[$oChild->getUid()]['children'] = $this->functionGetChildren($oChild);
        }
    }
    return $aChildrenToReturn;
}

=====

编辑:

这是我的数组的var_dump:

array (
  0 => 
  array (
    'name' => 'CEO',
    'id' => 1,
    'children' => 
    array (
      3 => 
      array (
        'name' => 'Director 1',
        'id' => 3,
        'children' => 
        array (
          4 => 
          array (
            'name' => 'Senior Manager 1',
            'id' => 4,
            'children' => 
            array (
              5 => 
              array (
                'name' => 'Manager 1',
                'id' => 5,
                'children' => 
                array (
                ),
              ),
            ),
          ),
        ),
      ),
      6 => 
      array (
        'name' => 'Director 2',
        'id' => 6,
        'children' => 
        array (
          7 => 
          array (
            'name' => 'Senior Manager 2',
            'id' => 7,
            'children' => 
            array (
            ),
          ),
        ),
      ),
    ),
  ),
)

=====

编辑:

我到目前为止已经使用过的

json_encode参数:JSON_FORCE_OBJECT

=====

编辑:

我现在已经成功生成了所需的数据结构。为此,我使用以下功能:

public function getRoleChildrenJson($aParentObject){
        $json = "";
        $i = 1;
        foreach($aParentObject['children'] as $aObject){
            $tmbObjectStr = "{name: \"".$aObject['name']."\",id: ".$aObject['id'];
            if(!empty($aObject['children'])){
                $tmbObjectStr .= ",children: [";
                $tmbObjectStr .= $this->getRoleChildrenJson($aObject);
                if($i < count($aParentObject['children'])){
                    $tmbObjectStr .= "]},";
                }
            }
            else{
                $tmbObjectStr .= "}]}";
            }
            $json .= $tmbObjectStr;
            $i++;
        }
        return $json;
    }

但是,现在最奇怪的事情发生了。尽管json字符串现在是准确的,但是当我第一次通过AJAX加载字符串时,jQUery插件仍然不接受它。即,以下可以起作用:

                        var data = [
                            {
                                name: 'node1', id: 1,
                                children: [
                                    { name: 'child1', id: 2 },
                                    { name: 'child2', id: 3 }
                                ]
                            },
                            {
                                name: 'node2', id: 4,
                                children: [
                                    { name: 'child3', id: 5 }
                                ]
                            }
                        ];
                        $('#rolestree').tree({
                            data: data
                        });

但是,以下无效

                ajaxRequest = $.ajax({
                    url: "/index.php" + $getData,
                    type: "POST",
                    data: "",
                    success: function (jsondata, textStatus, jqXHR) {
                        $('#rolestree').tree({
                            data: jsondata
                        });
                    }
                });

尽管非常相同的json字符串已通过AJAX完美加载(我已通过控制台进行了检查)。我首先需要评估或解析通过AJAX加载的数据吗?

1 个答案:

答案 0 :(得分:1)

如果您从PHP返回的json作为字符串,则必须在ajax响应中进行解析。

在ajax响应中添加内容类型

$.ajax({
          url: "/index.php" + $getData,
          type: "POST",                   data: "",
          success: function (jsondata, textStatus, jqXHR) {
                   console.log(jsondata);
                   var json = $.parseJSON(jsondata);

                   console.log(json);
                   $('#rolestree').tree({
                        data: json
                   });
          }
      });

致谢