0

我的意图是获取一系列字符串,用“_”分解它们并使用该数组中的键来构建一个“主”数组。

我的规则是:

if key no exists -> create key under parent array
if key exists -> add key as new array to parent
if key is last -> add value

字符串示例

total_players_count
total_rosters_count
players_season1_count
players_season2_count
rosters_season1_count

预期成绩

$main = array(
    'total' => array(
        'players'   => array(
            'count' => '123',
        'rosters'   => array(
            'count' => '123')
        )
    ),
    'players' => array(
        'season1'   => array(
            'count' => '123'
        )
    )
);

我希望这表明了我期望写的内容。现在让我来谈谈昨晚我是如何因一系列失败而让自己失望的;)

要点是,我的递归函数运行得不太好,所以我没有发布任何代码。我一直在使用 array_key_exists,但这并没有让我得到预期的结果。我使用 prev()、current() 和 end() 接近了但问题源于我必须解析的意外数量的键(否则我只会循环 3 次并完成。我知道如果我要解析的键数量有限;但我没有。

<?php
private function _get_section($parent_key, $sql) {

        $data = array();
        $data[$parent_key] = array();

        foreach ($sql AS $key => $value) {
            $keys       = explode('_', $key);

            if ($keys[0] == $parent_key) {
                $i          = 0;
                $total_keys = count($keys);

                for ($k = 1; $k < $total_keys; $k++) {
                    $i++;

                    if ($i == 1) {
                        echo '1. (' . $i . ') ' . $keys[$k];
                        $data[$parent_key][$keys[$k]] = array();
                    }
                    else if ($i > 1 && $i < $total_keys - 1) {
                        $data[$parent_key][$keys[$k - 1]][$keys[$k]] = array();
                    }
                    else if ($i == $total_keys - 1) {
                        $tmp = array_reverse($data);

                        // can't get the last key because I need to recursively loop 
                        // through the results to find where to set this last 
                        // key / value
                    }
                }
                $k      = 0;
                $i      = 0;
            }

            $keys       = array();
            $total_keys = 0;
        }
    }

解决方案(谢谢)

$tree = array();

foreach ($sql AS $key => $value) {
    $parts = explode('_', $key);

    $val = $value;

    foreach (array_reverse($parts) AS $part) {
        $val = array($part => $val);
    }
    $tree = array_merge_recursive($tree, $val);
}
4

1 回答 1

0

未经测试。希望我不需要阅读您的代码即可完全理解您想要什么,因为我没有。我只是看了预期的结果+输入,虽然我想知道发生了rosters_season1_count什么?

$tree = array();
foreach ($strings as $string) {
    $parts = explode('_', $string);
    $path = '123';
    foreach (array_reverse($parts) as $part) {
        $path = array($part => $path);
    }
    $tree = array_merge_recursive($tree, $path);
}
于 2012-10-19T16:12:54.537 回答