How do I declare a two dimensional array?

前端 未结 14 1582
爱一瞬间的悲伤
爱一瞬间的悲伤 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 22:02

    atli's answer really helped me understand this. Here is an example of how to iterate through a two-dimensional array. This sample shows how to find values for known names of an array and also a foreach where you just go through all of the fields you find there. I hope it helps someone.

    $array = array(
        0 => array(
            'name' => 'John Doe',
            'email' => 'john@example.com'
        ),
        1 => array(
            'name' => 'Jane Doe',
            'email' => 'jane@example.com'
        ),
    );
    
    foreach ( $array  as $groupid => $fields) {
        echo "hi element ". $groupid . "\n";
        echo ". name is ". $fields['name'] . "\n";
        echo ". email is ". $fields['email'] . "\n";
        $i = 0;
        foreach ($fields as $field) {
             echo ". field $i is ".$field . "\n";
            $i++;
        }
    }
    

    Outputs:

    hi element 0
    . name is John Doe
    . email is john@example.com
    . field 0 is John Doe
    . field 1 is john@example.com
    hi element 1
    . name is Jane Doe
    . email is jane@example.com
    . field 0 is Jane Doe
    . field 1 is jane@example.com
    

提交回复
热议问题