2

重複の可能性:
配列構造を持つ文字列から配列へ

私はそのような配列を持っています

$foo = array();
$foo['/'] = 'value';
$foo['/foo'] = 'value';
$foo['/foo/bar'] = 'value';
$foo['/test'] = 'value';
$foo['/test/tester'] = 'value';
$foo['/hello'] = 'value';
$foo['/hello/world'] = 'value';
$foo['/hello/world/blah'] = 'value';

私がする必要があるのは、これらのサブページをツリーのような構造に保存することです。代わりに、次のように自動的に変換する必要があります。

   $foo = array(
    '/' => array(
        'value' => 'value',
        'children' => array(
            '/foo' => array(
                'value' => 'value',
                'children' => array(
                    '/foo/bar' => array(
                        'value' => 'value',
                        'children' => array()
    );

私がやろうと思ったことは、次のようなものです:

$newArray = array();
foreach( $foo as $key => $val )
{
    $bits = explode('/', $key);

    foreach( $bits as $bit )
    {
        $newArray[$bit] = array('val' => $val);
    }
}

print_r($newArray);

ただし、何らかの方法で newArray にアクセスし、配列の深さを追跡する必要があります。誰かがどのようにそれを行ったかのサンプルスクリプトを持っているか、そうするためのファンキーな配列ウォークのヒントを持っていますか?

4

1 に答える 1

3

ソリューションは、変数参照 (別名「ポインター」) を使用して実現できます。詳細については、http://php.net/manual/en/language.references.phpを参照してください。

<?php

$foo = array();
$foo['/'] = 'value';
$foo['/foo'] = 'value';
$foo['/foo/bar'] = 'value';
$foo['/test'] = 'value';
$foo['/test/tester'] = 'value';
$foo['/hello'] = 'value';
$foo['/hello/world'] = 'value';
$foo['/hello/world/blah'] = 'value';

function nest(&$foo)
{
    $new = array();
    foreach ($foo as $path => $value)
    {
        $pointer =& $new;
        $currentPath = '';
        if ($pathParts = explode('/', trim($path, '/'))) {
            while($nextKey = array_shift($pathParts)) {
                $currentPath .= '/' . $nextKey;
                if (!isset($pointer['children'][$currentPath])) {
                    $pointer['children'][$currentPath] = array();
                }
                $pointer =& $pointer['children'][$currentPath];
            }
        }
        $pointer['value'] = $value;
    }
    return $new ? array('/' => $new) : array();
}

print_r($foo);
print_r(nest($foo));

?>
于 2012-06-14T17:38:36.703 に答える