开发者

Creating multidimensional array

开发者 https://www.devze.com 2023-03-17 00:45 出处:网络
I have array like this: $test = array(20, 30, 40); And I want to set a multi-dimension array with using these values: $example[20][30][40] = \'string\'

I have array like this: $test = array(20, 30, 40);

And I want to set a multi-dimension array with using these values: $example[20][30][40] = 'string'

How c开发者_C百科an I do this?

Note: "20, 30, 40" just an example, my program will print some integers, and I want to set a multi-dimension array with these values and it can be more than 3 values.


You could do it that way:

$example[$test[0]][$test[1]][$test[2]] = 'string'

Or if the size of the array is variable you will need to do a recursive function to fill up your array.

function fill_up($content, $value){
    $index = array_shift($content);
    if(count($content)){
        return array($index => fill_up($content, $value));
    } else {
        return array($index => $value);
    }
}

$example = array(20,30,40);
$value = 'test';
var_dump(fill_up($example, $value));


You can simply write :

 $example[19][29][39] = 'string'

Do not forget that the first element is 0 and not 1. This should work.


Look here:

http://php.net/manual/en/language.types.array.php

EXAMPLE:

$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar echo $arr[12]; // 1

EXPLANATION:

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

This can be expanded to n-dimensions. It's equivalent to an array within an array:

2-D ARRAY EXAMPLE:

$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42

'Hope that helps!


As 14moose seems to have been getting at, you can't make an empty array in PHP. It's not really an array. It's a map. You could certainly make a ridiculous multidimensional map using those input values, but that seems.. entirely useless.


<?php
$example = array();
$test = array(20, 30, 40);
foreach($test as $key=>$value)
{
   $example[$value] = $test;
}
print_r($example);exit;

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号