English 中文(简体)
dynamic array key additions
原标题:

Here is my precode...

$keys = array( a ,  b ,  c ,  d );
$number = 10;

And here is my code...

eval( $array[  .implode(  ][  ,$keys).  ] = $number; );

Using this, I get the following result...

Array (
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                            [d] => 10
                        )
                )
        )
)

Now, the problem is that this is the exact result I want, but I don t want to use eval().

As input to my code, I have a list of keys and a number. The number should be set to the value of the keys array being used to generate child-based keys for a certain array $array.

Is there a different way that I can achieve this? I don t want to overwrite the keys/numbers with new values as the code works - eval() preserves this already, so my new code should do the same.

最佳回答

Here is a full code example showing how it would work. Whats important is that you use a reference to the array so you can modify it:

<?php
    $keys = array( a ,  b ,  c ,  d ); 
    $number = 10;

    $org_array = array(
        "a" => "string",
        "z" => array( "k" => false)
      );

    function write_to_array(&$array, $keys, $number){
      $key = array_shift($keys);
      if(!is_array($array[$key])) $array[$key] = array();
      if(!empty($keys)){
        write_to_array($array[$key], $keys, $number);
      } else {
        $array[$key] = $number;
      }
    }

    write_to_array($org_array, $keys, $number);

    print_r($org_array);
?>
问题回答

Please note that the code below (which you evaluate) will generate a warning, and will therefore not work on projects with error reporting up to the max:

$array = array();
$array[ a ][ b ] = 42; // $array[ a ] is not an array... yet

Since you re using PHP 5, you can work with references to manipulate your array while traversing the branch of your tree that you wish to modify.

$current = & $array;

foreach ($keys as $key):

  if (!isset($current[$key]) || !is_array($current[$key]))
    $current[$key] = array();

  $current = & $current[$key];

endforeach;

$current = $value;

Edit: corrected for avoiding warnings and conflicts.

function deepmagic($levels, $value)
{
    if(count($levels) > 0)
    {
        return array($levels[0] => deepmagic(array_slice($levels, 1),
            $value));
    }
    else
    {
        return $value;
    }
}

$a = deepmagic(Array( a ,  b ,  c ,  d ), 10);

var_dump($a);

Output:

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(1) {
        ["d"]=>
        int(10)
      }
    }
  }
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签