【发布时间】:2017-03-22 11:06:33
【问题描述】:
我使用 jstree 来存储使用 JSON 的树结构。我的示例结构如下所示:
使用后
$treeJSONdecoded = json_decode($treeJSON, true);
我的 JSON 如下所示:
[0] => Array (
[id] => j1_1
[text] => Release1
[icon] => 1
[li_attr] => Array (
[id] => j1_1
)
[a_attr] => Array (
[href] => #
[id] => j1_1_anchor
)
[state] => Array (
[loaded] => 1
[opened] => 1
[selected] => 1
)
[data] => Array ( )
[children] => Array (
[0] => Array (
[id] => j1_3
[text] => List of features
[icon] => 1
[li_attr] => Array (
[id] => j1_3
)
[a_attr] => Array (
[href] => #
[id] => j1_3_anchor
)
[state] => Array (
[loaded] => 1
[opened] => 1
[selected] =>
)
[data] => Array ( )
[children] => Array (
[0] => Array (
[id] => j1_9
[text] => feature1
[icon] => 1
[li_attr] => Array (
[id] => j1_9
)
[a_attr] => Array (
[href] => #
[id] => j1_9_anchor
)
[state] => Array (
[loaded] => 1
[opened] =>
)
[data] => Array ( )
[children] => Array ( )
[type] => default
)
)
[type] => default
)
[1 => Array ( id] => j1_2
[text] => List of documents
[icon] => 1
[li_attr] => Array (
[id] => j1_2
)
[a_attr] => Array (
[href] => #
[id] => j1_2_anchor
)
[state] => Array (
[loaded] => 1
[opened] => 1
[selected] =>
)
[data] => Array ( )
[children] => Array (
[0] => Array (
[id] => j1_5
[text] => document1
[icon] => 1
[li_attr] => Array (
[id] => j1_5
)
[a_attr] => Array (
[href] => #
[id] => j1_5_anchor
)
[state] => Array (
[loaded] => 1
[opened] =>
)
[data] => Array ( )
[children] => Array ( )
[type] => default
)
)
[type] => default )
)
[type] => default
)
如何遍历整个 JSON 以获取“文本”值并拥有如下数组:
{"Release1", "List of features", ... , "document1"}
假设我不知道有多少级别。我尝试了类似
foreach($treeJSONdecoded as $val){
echo $val['text'];
}
只是想看看我能获取什么,但它似乎不起作用。
【问题讨论】:
-
查看 RecursiveIterator / RecursiveIteratorIterator (lol),它将帮助您循环遍历嵌套的数组结构。
-
仔细看看数组结构!数组右侧部分的 foreach 只需 find
-
语句“假设我不知道有多少层”意味着在某种程度上需要递归。