一. 创建数组
1. 创建空数组
<?php
$arr1 = array();
var_dump($arr1);
echo '<hr>';
$arr2 = [];
var_dump($arr2);
?>
2. 创建索引数组
<?php
$arr1 = array(
'张三',
'李四',
'王五'
);
var_dump($arr1);
echo '<hr>';
print_r($arr1);
echo '<hr>';
$arr2 = [
'苹果',
'小米',
'大米'
];
var_dump($arr2);
echo '<hr>';
print_r($arr2);
echo '<hr>';
?>
3. 创建关联数组
<?php
$arr1 = array(
'name' => '张三',
'sex' => '男',
'age' => 18
);
var_dump($arr1);
echo '<hr>';
$arr2 = [
'zs' => '张三',
'ls' => '李四',
'ww' => '王五'
];
var_dump($arr2);
echo '<hr>';
?>
4. 输出数组值
<?php
$arr1 = [
'张三',
'李四',
'王五'
];
echo $arr1[0] . ' ' . $arr1[1] . ' ' . $arr1[2];
echo '<hr>';
$arr2 = [
'ouyangke' => '欧阳克',
'zhulaoshi' => '朱老师',
'ximen' => '西门大官人'
];
echo $arr2['ouyangke'];
echo '<br>';
echo $arr2['zhulaoshi'];
echo '<br>';
echo $arr2['ximen'];
echo '<br>';
?>
二. 多维数组
1. 二维数组
<?php
$arr = [
[
'name' => '张三',
'sex' => '男',
'age' => 18
],
[
'name' => '李四',
'sex' => '男',
'age' => 19
],
[
'name' => '王五',
'sex' => '男',
'age' => 21
]
];
var_dump($arr);
echo '<hr>';
print_r($arr);
?>
2. 三维数组
<?php
$arr = [
[
'name' => '张三',
'sex' => '男',
'age' => 18,
'job' => [
'java程序员',
'画家'
]
],
[
'name' => '李四',
'sex' => '男',
'age' => 19,
'job' => [
'php程序员',
'架构师'
]
],
[
'name' => '王五',
'sex' => '男',
'age' => 21,
'job' => [
'python程序员',
'快递员'
]
]
];
var_dump($arr);
echo '<hr>';
print_r($arr);
?>
3. 多维数组访问
echo $arr[0]['name'] . '---' . $arr[0]['job'][0];
echo '<hr>';
echo $arr[1]['name'] . '---' . $arr[1]['job'][0];
echo '<hr>';
echo $arr[2]['name'] . '---' . $arr[2]['job'][0];
echo '<hr>';
三. 多维数组循环
1. 二维数组循环
<?php
$arr = [
[
'name' => '欧阳克',
'age' => 18
],
[
'name' => '朱老师',
'age' => 20
],
[
'name' => '西门大官人',
'age' => 24
]
];
foreach ( $arr as $v ) {
echo $v['name'] . '--' . $v['age'];
echo '<br>';
}
echo '<hr>';
foreach ( $arr as $v ) {
foreach ( $v as $vv ) {
echo $vv;
echo '<br>';
}
}
echo '<hr>';
foreach ( $arr as $k=>$v ) {
foreach ( $v as $kk=>$vv ) {
echo $kk . ' ' . $vv;
echo '<br>';
}
}
?>
2. 三维数组循环
<?php
$arr = [
[
'name' => '张三',
'sex' => '男',
'age' => 18,
'job' => [
'java程序员',
'画家'
]
],
[
'name' => '李四',
'sex' => '男',
'age' => 19,
'job' => [
'php程序员',
'架构师'
]
],
[
'name' => '王五',
'sex' => '男',
'age' => 21,
'job' => [
'python程序员',
'快递员'
]
]
];
foreach ($arr as $value) {
echo $value['name'];
foreach ($value['job'] as $vv) {
echo '---' . $vv;
}
echo '<br>';
}
echo '<hr>';
foreach ( $arr as $value ) {
foreach ( $value as $k=>$v ) {
foreach ( $v as $vv ) {
echo $vv;
echo '<br>';
}
}
echo '<hr>';
}
?>
四. 总结
通过以上实例练习,学会了数组的相关知识,特别是对数组的循环有了较为深刻的理解。