什么是数据容器?
所谓的数据容器就是存放多个数据的变量类型, 就称之为数据容器, 在 JS 中有数组/对象, 在 Python 中有 数组/元组/字典/Set 等
注意
在 PHP 中, 数据容器只有 数组/对象, 其他的什么元组/字典/Set都没有, 虽然这些类型都没有, 但是使用 PHP 的数组可以达到类似的效果
数组
php
<?php
### 1.定义数组
# 1.1 兼容骨灰版本的 php 的写法
$arr1 = array("a", "b", "c");
# 1.2 PHP 5.4 之后的新版本的写法
$arr2 = ["d", "e", "f"];
### 2.查看类型
echo "<pre>";
echo gettype($arr1); // array
echo "<br/>";
echo gettype($arr2); // array
### 3.获取数组的长度
echo "<br />";
echo count($arr1); // 3
echo "<br/>";
echo count($arr2); // 3
### 3.遍历数组
# 3.1 foreach 遍历数组(推荐)
echo "<hr />";
foreach ($arr1 as $key => $value) {
echo $key . "=>" . $value . "<br/>";
// 输出:
// 0=>a
// 1=>b
// 2=>c
}
# 3.2 for + count 遍历数组(不推荐)
echo "<hr />";
for ($i = 0; $i < count($arr2); $i ++) {
echo $i . "=>" . $arr2[$i] . "<br/>";
// 输出:
// 0=>d
// 1=>e
// 2=>f
}
echo "</pre>";自定义下标的数组
类似 dict 字典的数据(但是在PHP中,他就是 array 类型,所以是数组)
php
<?php
$dict = [
"name" => "tom",
"age" => 20,
"email" => "test@example.com"
];
echo gettype($dict); // array
echo "<br />";
// 遍历数组
foreach ($dict as $key => $value) {
echo $key . "=>" . $value . "<br />";
// 输出:
// name => tom
// age => 20
// email => test@example.com
}
// 所以现在知道为什么不推荐 for + count 遍历数组了吗?
// 因为那种方式: 是使用 $i 当作下标, 只要是这种自定义的下标
// 使用 $i 就无法获取到值了
for($i = 0; $i < count($dict); $i++) {
echo $i . "=>" . $dict[$i] . "<br />";
// 输出错误信息如下:
// Warning: Undefined array key 0 in index.php on line 28
// 0=>
//
// Warning: Undefined array key 1 in index.php on line 28
// 1=>
//
// Warning: Undefined array key 2 in index.php on line 28
// 2=>
}混合下标的数组
php
<?php
$arr = [
"hello", // 下标: 0(integer) 值: (boolean) 我也不明白为什么不是 string 而是 boolean
1 => "world", // 下标: 1(integer) 值: world(string)
"name" => "tom", // 下标: name(string) 值: tom(string)
-1 => -1, // 没有找到, 被覆盖了(说明下标会专为字符串,再去设置/获取值 -> HashMap)
"-1" => "-1str", // 下标: -1(integer) 值: -1str(string)
null => "1", // 下标: (string) 值: 1(string) -> null 被专为了空字符串'', 所以无法显示出来
false => false, // 没有: 说明布尔类型的值无法作为下标
// 1.1 => 1.1, 报错: Deprecated: Implicit conversion from float 1.1 to int loses precision in index.php
];
foreach ($arr as $key => $val) {
$key_type = gettype($key);
$val_type = gettype($val);
echo "{$key}({$key_type}) => {$val}({$val_type}) <br>";
}
foreach ($arr as $key => $val) {
$key_type = gettype($key);
$val_type = gettype($val);
echo "{$key}({$key_type}) => {$val}({$val_type}) <br>";
}PHP 数组键的完整转换规则
- 键指的是 "下标", 或者叫 "索引"
- PHP 数组只接受两种键类型: 整数(integer) 和字符串(string)
- 所有其他类型的下标都会被自动转换为整数或字符串 -> 先尝试转数字 -> 不行再尝试转字符串
- 转换发生在赋值时,不是在访问时
- 所有整数/字符串的下标直接保留
- 空字符串也是有效下标
- 未指定下标的自动分配一个 integer 类型的下标
php
<?php
# 自动分配 下标的 规则
$arr = [
'first', // 下标 = 0
10 => 'explicit', // 下标 = 10
'third', // 下标 = 11 (前一个整数键+1)
'name' => 'tom', // 下标 = name, 字符串键
'fifth', // 下标 = 12 (继续从11递增)
];