PHP:如何基于我获得的某些值动态创建多维数组?

时间:2015-10-14 13:01:21

标签: php arrays multidimensional-array

以此数组为例:

$array = array( 'key1' , 'key2'   );

如何使用上面的数组创建这样的内容:

$multiarray['key1']['key2'] = 'test'; 

无论数组计数如何,这都应该有效:

$array = array( 'key1' , 'key2' , 'key3' , 'key4'   );

$multiarray['key1']['key2']['key3']['key4'] = 'test'; 

4 个答案:

答案 0 :(得分:0)

有点超出范围,但值得一提的是我相信:)

$foo = new stdClass;
$foo->foo->bar->baz->qux = "¯\_(ツ)_/¯";

print_r($foo);

输出:

stdClass Object
(
    [foo] => stdClass Object
        (
            [bar] => stdClass Object
                (
                    [baz] => stdClass Object
                        (
                            [qux] => ¯\_(ツ)_/¯
                        )

                )

        )

)

答案 1 :(得分:0)

怎么样:

<?php
$ks = [3,2,4,1,4,5,5521,231,3];

var_dump(array_reduce( array_reverse($ks)
                      ,function($carry,$item){ return [$item => $carry];}
                      ,"test"));

/* array(1) {
  [3]=>
  array(1) {
    [2]=>
    array(1) {
      [4]=>
      array(1) {
        [1]=>
        array(1) {
          [4]=>
          array(1) {
            [5]=>
            array(1) {
              [5521]=>
              array(1) {
                [231]=>
                array(1) {
                  [3]=>
                  string(4) "test"
                }
              }
            }
          }
        }
      }
    }
  }
} */
?>

答案 2 :(得分:0)

另一种观点,即使用spongeBob作为functionname:

$inp = ['keyX', 'koyX', 'drip', 'drop'];
$result = spongeBob($inp);

echo "<pre>";
print_r($result);
echo "</pre>"; 

function spongeBob($arr){
    $rev = array_reverse($arr);
    $result = 'test';
    foreach ($rev as $oneKey){
        $result = array($oneKey => $result);
    }   
    return $result;
}

答案 3 :(得分:0)

这个怎么样 -

rfact:
        pushl   %ebp

.L3:
movl    %esp, %ebp
pushl   %ebx
subl    $4, %esp
movl    8(%ebp), %ebx
movl    $1, %eax
cmpl    $1, %ebx
jle     .L3
leal    -1(%ebx), %eax
movl    %eax, (%esp)
call    rfact
imull   %ebx, %eax
addl    $4, %esp
popl    %ebx
popl    %ebp
ret

<强>输出

<?php
$array = array( 'key1' , 'key2' , 'key3' , 'key4'   );
$result=magic();
function magic()
{
global $array;
$key=current($array);
return next($array)?array($key=>magic()):array($key=>'text');

}
echo "<pre>";
print_r($result);
echo "<pre>";

?>