最後,如果你想從一個不知名的扁平化下來樹深度,你需要遞歸。我嘲笑你的樣本對象的一個稍微更廣泛的例子在一個文件中(「test.json」):
{
"new": false,
"properties": {
"children": [
{
"new": false,
"properties": {
"children": [],
"id": 188,
"lft": 17,
"name": "dood dood",
"parent_id": 180,
"rght": 18
},
"repository": "Teams"
},
{
"new": false,
"properties": {
"children": [],
"id": 182
},
"repository": "Teams"
}
],
"id": 180,
"lft": 16,
"name": "Herp de Derp",
"parent_id": 169,
"rght": 19
},
"repository": "Teams"
}
我在PHP創建通過此列舉的一個例子程序如下圖所示:
<?php
// $x is the JSON representation of this object (quick for scaffolding purposes)
// $y is the object representation
$x = file_get_contents("test.json");
$y = json_decode($x);
// $memo is our final product, an array that is written to as we traverse the object's children
$memo = [];
// Using recursive closure to walk the object/children and append to $memo
$z = function($n) use (&$z, &$memo) {
// Build clone $o (sans children) of $n:
$o = new stdClass;
$o->new = $n->new;
$o->repository = $n->repository;
$o->properties = [];
$children = [];
foreach($n->properties as $k => $v) {
if($k == "children") {
// Do children afterward, to ensure current object
// appears in array before children
$children = $v;
continue;
} else {
$o->properties[$k] = $v;
}
}
array_push($memo, $o);
array_walk($children, $z);
};
$z($y);
print_r($memo);
$z
是我的遞歸函數,我選擇將它作爲優先級的閉包實現。我首先分配一個空數組($memo
),然後通過首先添加當前對象來填充,然後在事實之後添加對象的子對象。當它遍歷子元素時,遞歸函數會自動爲其子元素調用,如有必要,等等。
通過上述,我的輸出表現爲:
Array
(
[0] => stdClass Object
(
[new] =>
[repository] => Teams
[properties] => Array
(
[id] => 180
[name] => Herp de Derp
[parent_id] => 169
[lft] => 16
[rght] => 19
)
)
[1] => stdClass Object
(
[new] =>
[repository] => Teams
[properties] => Array
(
[id] => 188
[name] => dood dood
[parent_id] => 180
[lft] => 17
[rght] => 18
)
)
[2] => stdClass Object
(
[new] =>
[repository] => Teams
[properties] => Array
(
[id] => 182
)
)
)
你看着陣的問題,但你的數據是一個對象,你嘗試轉換爲數組,然後在它 – Dale 2014-09-26 18:18:34
呀我正在運行的其他想法m運行'toArray'(CakePHP 3命令),它應該已經轉換了它,所以我認爲調試只是轉換前的對象表示。我會盡量快速確認。 – 2014-09-26 18:23:51