<?php
declare(strict_types=1);
$cases = [];
// Case 1: 2D indexed array ($cars) with auto-assigned 0-based keys
(function () use (&$cases): void {
$cars = [
['Volvo', 100, 96],
['BMW', 60, 59],
['Toyota', 110, 100],
];
$actual = [
'outer_keys' => array_keys($cars),
'first_brand' => $cars[0][0],
'bmw_sold' => $cars[1][2],
'toyota_stock' => $cars[2][1],
'row_count' => count($cars),
'recursive_count' => count($cars, COUNT_RECURSIVE),
];
$expected = [
'outer_keys' => [0, 1, 2],
'first_brand' => 'Volvo',
'bmw_sold' => 59,
'toyota_stock' => 110,
'row_count' => 3,
'recursive_count' => 12,
];
$cases[] = [
'name' => 'two_d_indexed_cars_matrix',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 2: 2D associative array with string keys and nested element indexing
(function () use (&$cases): void {
$sites = [
'php' => ['PHP 官方手册', 'https://www.php.net'],
'mdn' => ['MDN 文档', 'https://developer.mozilla.org'],
'w3c' => ['W3C 规范', 'https://www.w3.org'],
];
$printed = print_r($sites, true);
$actual = [
'keys' => array_keys($sites),
'php_line' => $sites['php'][0] . '地址为:' . $sites['php'][1],
'mdn_url' => $sites['mdn'][1],
'print_r_has_php_key' => str_contains($printed, '[php] => Array'),
];
$expected = [
'keys' => ['php', 'mdn', 'w3c'],
'php_line' => 'PHP 官方手册地址为:https://www.php.net',
'mdn_url' => 'https://developer.mozilla.org',
'print_r_has_php_key' => true,
];
$cases[] = [
'name' => 'two_d_associative_sites',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
// Case 3: 3D array nesting, direct access, and recursive traversal
(function () use (&$cases): void {
$cube = [
[
[1, 2],
[3, 4],
],
[
[5, 6],
[7, 8],
],
];
$flat = [];
foreach ($cube as $layer) {
foreach ($layer as $row) {
foreach ($row as $val) {
$flat[] = $val;
}
}
}
$actual = [
'element_1_0_1' => $cube[1][0][1],
'element_0_1_0' => $cube[0][1][0],
'flattened' => $flat,
'sum' => array_sum($flat),
'depth_check_is_array' => is_array($cube[0][0]),
];
$expected = [
'element_1_0_1' => 6,
'element_0_1_0' => 3,
'flattened' => [1, 2, 3, 4, 5, 6, 7, 8],
'sum' => 36,
'depth_check_is_array' => true,
];
$cases[] = [
'name' => 'three_d_cube_traversal',
'passed' => $actual === $expected,
'expected' => $expected,
'actual' => $actual,
];
})();
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、PHP 8.4 本地 CLI 环境。
入口文件:projects/php-arrays-multi-lab/explore-arrays-multi.php
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-arrays-multi.php,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1230.zip