【问题标题】:How to convert PHP array to JS Nested Array of Objects如何将 PHP 数组转换为 JS 嵌套对象数组
【发布时间】:2019-06-26 23:05:19
【问题描述】:

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

我已经尝试对 PHP 数组 json_encode,但得到的结果与 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 加载的这些数据?

【问题讨论】:

  • 请向我们展示您的尝试。我们确实想帮助您解决现有代码中的问题,但我们并不是要为您完成所有工作。
  • 请添加一个示例 PHP 数组,我们可以用它来测试它(而不是它的 var_dump 表示)以及您使用的确切 json_encode 参数。
  • 您需要在 php 中构建正确的数据结构,然后使用 json_encode() 在 javascript 中使用它。 array_values() 将帮助您将 php 数组转换为“真实”/从零开始的数值数组。
  • 看看你是如何创建这个 PHP 数组的可能会很有用。我相信它可以通过一种符合您要求的方式来完成,而不是试图将这个数组 FUDGE 变成所需的
  • @ChrisG 我想你要的是var_export()仅供参考

标签: javascript php


【解决方案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
                   });
          }
      });

问候

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2017-11-15
    • 2021-07-12
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多