ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## :-: 一、`php` 创建数组 ### 1、创建空数组 ```php $arr = array(); var_dump( $arr ); $arrs = []; var_dump( $arrs ); ``` ### 2、创建索引数组 ```php $arr = array( '欧阳克', '黄蓉', '郭靖' ); var_dump( $arr ); $arrs = [ '欧阳克', '黄蓉', '郭靖' ]; var_dump( $arrs ); ``` ### 3、创建关联数组 ```php $arr = array( 'ouyangke' => '欧阳克', 'huangrong' => '黄蓉', 'guojing' => '郭靖' ); var_dump( $arr ); $arrs = [ 'ouyangke' => '欧阳克', 'huangrong' => '黄蓉', 'guojing' => '郭靖' ]; var_dump( $arrs ); ``` ### 4、输出数组值 ```php $arr = [ '欧阳克', '黄蓉', '郭靖' ]; echo $arr[0]; echo '<hr>'; echo $arr[1]; echo '<hr>'; echo $arr[2]; echo '<hr>'; $arrs = [ 'ouyangke' => '欧阳克', 'huangrong' => '黄蓉', 'guojing' => '郭靖' ]; echo $arrs['ouyangke']; echo '<hr>'; echo $arrs['huangrong']; echo '<hr>'; echo $arrs['guojing']; echo '<hr>'; ``` ### 5、打印数组 `print_r` ```php $arr = [ '欧阳克', '黄蓉', '郭靖' ]; print_r($arr); ``` --- ## :-: 二、`php` 多维数组 > 备:数组最好不要超过3层 ### 1、二维数组 ```php $arr = array( array( 'name' => '欧阳克', 'age' => 18, ), array( 'name' => '黄蓉', 'age' => 16, ), array( 'name' => '郭靖', 'age' => 22, ) ) var_dump($arr); print_r($arr); ``` ### 2、三维数组 ```php $arr = [ [ 'name' => '欧阳克', 'age' => 18, 'gongfu' => [ '神驼雪山拳', '灵蛇拳法' ] ], [ 'name' => '黄蓉', 'age' => 16,, 'gongfu' => [ '碧波掌法', '落英神剑掌' ] ], [ 'name' => '郭靖', 'age' => 22,, 'gongfu' => [ '降龙十八掌', '九阴真经' ] ] ]; var_dump($arr); print_r($arr); ``` ### 3、多维数组访问 > 备:数组访问时,层次不要弄错 ```php $arr = [ [ 'name' => '欧阳克', 'age' => 18, 'gongfu' => [ '神驼雪山拳', '灵蛇拳法' ] ], [ 'name' => '黄蓉', 'age' => 16,, 'gongfu' => [ '碧波掌法', '落英神剑掌' ] ] ] echo $arr[0]['name'].' --- '; echo $arr[0]['gongfu'][0].' --- '; echo $arr[0]['gongfu'][1]; ``` --- ## :-: 三、`php` 数组循环 * 数组循环,是对二维数组以上的数组进行循环 ### 1、`foreach` ```php $arr = array( 'ouyangke' => '欧阳克', 'huangrong' => '黄蓉', 'guojing' => '郭靖' ); foreach( $arr as $v ){ echo $v; echo '<hr>'; } ``` ### 2、`key` 和 `value` ```php 示例1: $arr = array[ 'ouyangke' => '欧阳克', 'huangrong' => '黄蓉', 'guojing' => '郭靖' ]; foreach( $arr as $k=>$v ){ echo $k . ' --- ' . $v; echo '<hr>'; } ``` ```php 示例2: $arr = [ '欧阳克', '黄蓉', '郭靖' ]; foreach( $arr as $k=>$v ){ echo $k . ' --- ' . $v; echo '<hr>'; } ``` ### 3、循环多维数组 ```php 示例1: $arr = [ [ 'name' => '欧阳克', 'age' => 18 ], [ 'name' => '黄蓉', 'age' => 16 ], [ 'name' => '郭靖', 'age' => 22 ] ]; foreach( $arr as $k=>$v ){ print_r($v); echo '<hr>'; } ``` ```php 示例2: $arr = [ [ 'name' => '欧阳克', 'age' => 18 ], [ 'name' => '黄蓉', 'age' => 16 ], [ 'name' => '郭靖', 'age' => 22 ] ]; foreach( $arr as $k=>$v ){ foreach ($v as $key => $value) { echo $value; echo '<hr>'; } } ``` ```php 示例3: $arr = [ [ 'name' => '欧阳克', 'age' => 18 ], [ 'name' => '黄蓉', 'age' => 16 ], [ 'name' => '郭靖', 'age' => 22 ] ]; foreach( $arr as $k=>$v ){ echo $v['name'].' --- '.$v['age']; echo '<hr>'; } ```