How do I declare a two dimensional array?

前端 未结 14 1525
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 21:46

What\'s the easiest way to create a 2d array. I was hoping to be able to do something similar to this:

declare int d[0..m, 0..n]
相关标签:
14条回答
  • 2020-11-29 21:48
    $r = array("arr1","arr2");
    

    to echo a single array element you should write:

    echo $r[0];
    echo $r[1];
    

    output would be: arr1 arr2

    0 讨论(0)
  • 2020-11-29 21:51

    As far as I'm aware there is no built in php function to do this, you need to do it via a loop or via a custom method that recursively calls to something like array_fill inidcated in the answer by @Amber;

    I'm assuming you mean created an empty but intialized array of arrays. For example, you want a final results like the below of a array of 3 arrays:

       $final_array = array(array(), array(), array());
    

    This is simple to just hand code, but for an arbitrary sized array like a an array of 3 arrays of 3 arrays it starts getting complex to initialize prior to use:

         $final_array = array(array(array(), array(), array()), array(array(), array(), array()), array(array(), array(), array()));
    

    ...etc...

    I get the frustration. It would be nice to have an easy way to declare an initialized array of arrays any depth to use without checking or throwing errors.

    0 讨论(0)
  • 2020-11-29 21:52

    You can try this, but second dimension values will be equals to indexes:

    $array = array_fill_keys(range(0,5), range(0,5));

    a little more complicated for empty array:

    $array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));

    0 讨论(0)
  • 2020-11-29 21:53

    For a simple, "fill as you go" kind of solution:

    $foo = array(array());

    This will get you a flexible pseudo two dimensional array that can hold $foo[n][n] where n <= ∞ (of course your limited by the usual constraints of memory size, but you get the idea I hope). This could, in theory, be extended to create as many sub arrays as you need.

    0 讨论(0)
  • 2020-11-29 21:57

    You need to declare an array in another array.

    $arr = array(array(content), array(content));

    Example:

    $arr = array(array(1,2,3), array(4,5,6));

    To get the first item from the array, you'll use $arr[0][0], that's like the first item from the first array from the array. $arr[1][0] will return the first item from the second array from the array.

    0 讨论(0)
  • 2020-11-29 22:01

    The following are equivalent and result in a two dimensional array:

    $array = array(
        array(0, 1, 2),
        array(3, 4, 5),
    );
    

    or

    $array = array();
    
    $array[] = array(0, 1, 2);
    $array[] = array(3, 4, 5);
    
    0 讨论(0)
提交回复
热议问题