## 前言 本文章并不对文章所涉及的知识点进行扫盲,如果您未接触过文章中所涉及的知识点请花点时间了解学习。 ## 涉及知识点 1. `Visual Studio Code` 2. `launch.json` 3. `tasks.json` - 阅读剩余部分 -
- 阅读剩余部分 -
## 名称定义 - 索引数组:所有键名都为数值型,注意字符串类型的数字键名会被转换为数值型。 - 连续索引数组:键名是连续性的数字。 - 关联数组:所有键名都为字符串型,注意字符串类型的数字键名会被转换为数值型。 - 混合数组:键名既有数值型也有字符串型。 ## 代码 ```php /** * 判断数组是否为索引数组 */ function is_indexed_array($arr) { if (is_array($arr)) { return count(array_filter(array_keys($arr), 'is_string')) === 0; } return false; } /** * 判断数组是否为连续的索引数组 * 以下这种索引数组为非连续索引数组 * [ * 0 => 'a', * 2 => 'b', * 3 => 'c', * 5 => 'd', * ] */ function is_continuous_indexed_array($arr) { if (is_array($arr)) { $keys = array_keys($arr); return $keys == array_keys($keys); } return false; } /** * 判断数组是否为关联数组 */ function is_assoc_array($arr) { if (is_array($arr)) { // return !is_indexed_array($arr); return count(array_filter(array_keys($arr), 'is_string')) === count($arr); } return false; } /** * 判断数组是否为混合数组 */ function is_mixed_array($arr) { if (is_array($arr)) { $count = count(array_filter(array_keys($arr), 'is_string')); return $count !== 0 && $count !== count($arr); } return false; } ``` ## 耗时测试 ```php // 对百万数组进行千次的循环判断 $arr = []; for ($i = 0; $i < 1000000; $i++) { $j = 0; $key = mt_rand(1, 100) >= 50 ? $j++ : md5(time(true)); $arr[$key] = md5(time(true) . time(true)); } $t = microtime(true); for ($i = 0; $i < 1000; $i++) { is_indexed_array($t); } echo microtime(true) - $t, "s\n"; $t = microtime(true); for ($i = 0; $i < 1000; $i++) { is_assoc_array($t); } echo microtime(true) - $t, "s\n"; $t = microtime(true); for ($i = 0; $i < 1000; $i++) { is_continuous_indexed_array($t); } echo microtime(true) - $t, "s\n"; $t = microtime(true); for ($i = 0; $i < 1000; $i++) { is_mixed_array($t); } echo microtime(true) - $t, "s\n"; // 输出 // 0.0019919872283936s // 0.0020020008087158s // 0.0021991729736328s // 0.0019669532775879s ``` ## 测试结果 对百万数组进行千次的循环判断均为毫秒级