简体   繁体   中英

PHP: Most Efficient way in initializing large amount of multidimensional array?

What is the most efficient way in initializing large amount of multidimensional array in PHP?

example: I'm going to create 100 Multidimensional array that look like this:

Array
(
    [1] => Array
        (
            [multi] => 1
        )

    [2] => Array
        (
            [multi] => 2
        )

    [3] => Array
        (
            [multi] => 3
        )

    [4] => Array
        (
            [multi] => 4
        )

    [5] => Array
        (
            [multi] => 5
        )
      .......
)

Currently, I'm using this code to create the array shown above:

// 100 arrays
for($i=1; $i<=100; $i++){
   $array[$i]['multi']=$i;
}

I also found an alternative way by using array_fill() and array_fill_keys() , but It only allows the same value to be initialized in an array:

$array = array_fill(1, 100, array_fill_keys(array("multi"), "value_here"));

QUESTION: Is there a more efficient way in initializing this kind of array in terms of speed?

You could use array_map over the range of values you want:

$array = array_map(function ($v) { return array('multi' => $v); }, range(0, 5));
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [multi] => 0
        )
    [1] => Array
        (
            [multi] => 1
        )
    [2] => Array
        (
            [multi] => 2
        )
    [3] => Array
        (
            [multi] => 3
        )
    [4] => Array
        (
            [multi] => 4
        )
    [5] => Array
        (
            [multi] => 5
        )
)

If you don't want the 0 element, just unset($array[0]);

Demo on 3v4l.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM