如何使用深度变量创建多维数组

时间:2018-12-21 15:46:00

标签: php loops multidimensional-array

我有两个单数组。数据和deep_level。

VSS.init({
            explicitNotifyLoaded: true,
            usePlatformScripts: true,
            usePlatformStyles: true
        });

        VSS.require(["VSS/Service", "TFS/WorkItemTracking/RestClient"], function (VSS_Service, TFS_Wit_WebApi) {

                var projectId = VSS.getWebContext().project.id;
                var witClient = VSS_Service.getCollectionClient(TFS_Wit_WebApi.WorkItemTrackingHttpClient)
                var query = {
                    query: "Select [System.Id] From WorkItems Where [System.WorkItemType] = 'Bug' order by [System.CreatedDate] asc"
                };

                witClient.queryByWiql(query, projectId).then(
                    function (result) {

                        var openWorkItems = result.workItems.map(function (wi) { 
                            return wi.id; 
                        });

                        var fields = [
                            "System.Title",
                            "System.CreatedDate"
                        ];

                        witClient.getWorkItems(openWorkItems, fields).then(
                            function (workItems) {
                                //
                                //how do I retrieve workitem fields here
                                //
                            });
                    });
        });

// data
array {
  [0] => "orders",
  [1] => "order",
  [2] => "id",
  [3] => "code",
  [4] => "products",
  [5] => "product",
  [6] => "id",
  [7] => "title",
  [8] => "variants",
  [9] => "variant",
  [10] => "id",
  [11] => "param",
  [12] => "options",
  [13] => "option",
  [14] => "id",
  [15] => "param"
}

key($ data)== key($ deep_level)

如何从这些数据中创建多维数组

// deep_level
array {
  [0] => 0,
  [1] => 1,
  [2] => 2,
  [3] => 2,
  [4] => 2,
  [5] => 3,
  [6] => 4,
  [7] => 4,
  [8] => 4,
  [9] => 5,
  [10] => 6,
  [11] => 6,
  [12] => 4,
  [13] => 5,
  [14] => 6,
  [15] => 6
}

深度级别不是固定的,可以更深或更小。我认为,这可能是递归array(1) { ["orders"] => array { ["order"] => array { ["id"] => null, ["title"] => null, ["products"] => array { ["product"] => array { ["id"] => null, ["title"] => null, ["variants"] => array { ["variant"] => array { ["id"] => null, ["param"] => null } }, ["options"] => array { ["option"] => array { ["id"] => null, ["param"] => null } } } } } } } 的问题,但我是新手。

1 个答案:

答案 0 :(得分:1)

在您的情况下,如果您遍历数组并将对先前级别的引用存储在数组中,则无需递归即可完成此操作。这样做,整个过程变得非常简单。

function buildTree($data, $deep) {
    $tree = [];
    $levels = [0 => &$tree];
    foreach ($data as $i => $item) {
        $level = $deep[$i];
        $pos = max(0, $level - 1);
        $levels[$pos][$item] = [];
        $levels[$level] = &$levels[$pos][$item];
        $current = $level;
    }

    return $tree;
}

请注意,此方法没有错误检查,因此您的深层数组应该有效并以0开头,否则输出将为任何值,但不是您期望的值。