概要
閲覧数:2651
投稿日:2016-01-18
更新日:2016-01-18
連想配列に、再帰処理をかけてツリー状の連想配列を生成
・添字に値を格納
・末端のみ値を数値として格納
コード
$tourist_spot = array(
'a' => array('日本','東京都','台東区','浅草','浅草寺',10),
'b' => array('日本','東京都','千代田区','大手町','首塚',5),
'c' => array('日本','千葉県','浦安市','舞浜','ディズニーランド',10),
'd' => array('日本','東京都','台東区','浅草','浅草演芸ホール',7),
);
$tree = array();
foreach ($tourist_spot as $spot) {
$current = &$tree;
foreach (array_slice($spot, 0, -1) as $segment) {
if (!isset($current[$segment])) {
$current[$segment] = array();
}
$current = &$current[$segment];
}
$current = current(array_slice($spot, -1));
}
unset($current);
print_r($tree);
結果
Array
(
[日本] => Array
(
[東京都] => Array
(
[台東区] => Array
(
[浅草] => Array
(
[浅草寺] => 10
[浅草演芸ホール] => 7
)
)
[千代田区] => Array
(
[大手町] => Array
(
[首塚] => 5
)
)
)
[千葉県] => Array
(
[浦安市] => Array
(
[舞浜] => Array
(
[ディズニーランド] => 10
)
)
)
)
)