You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印带递增键的多维数组?附学生与作者数组示例

嘿,我来帮你搞定这个带递增键的多维数组打印需求!先明确下我们要处理的两个数组结构(我把你没写完的$selection子数组补全了,方便演示):

// 学生姓名数组
$student = ['Jane', 'Michelle', 'Mark'];

// 作者选择多维数组
$selection = [
    ['Mark Twaine', 'E A Poe', 'James Joyce'],
    ['Charles Dickens', 'Emily Bronte', 'George Orwell'],
    ['Ernest Hemingway', 'F. Scott Fitzgerald', 'John Steinbeck']
];

接下来分两种常见的递增键需求给你方案:

一、每个学生的选择项单独递增(从1开始)

这种是最常用的,每个学生的作者选择都从1开始编号,代码实现如下:

function printStudentSelections($students, $selections) {
    foreach ($students as $index => $studentName) {
        echo "=== {$studentName} 的作者选择 ===\n";
        // 容错:检查当前学生是否有对应的选择数组
        if (isset($selections[$index]) && is_array($selections[$index])) {
            foreach ($selections[$index] as $key => $author) {
                // 把默认的0索引转为从1开始的递增键
                $incrementKey = $key + 1;
                echo "{$incrementKey}. {$author}\n";
            }
        } else {
            echo "该学生没有选择任何作者\n";
        }
        echo "\n"; // 分隔不同学生的内容,更易读
    }
}

// 调用函数执行打印
printStudentSelections($student, $selection);

运行后输出效果大概是:

=== Jane 的作者选择 ===
1. Mark Twaine
2. E A Poe
3. James Joyce

=== Michelle 的作者选择 ===
1. Charles Dickens
2. Emily Bronte
3. George Orwell

=== Mark 的作者选择 ===
1. Ernest Hemingway
2. F. Scott Fitzgerald
3. John Steinbeck

二、全局所有选择项连续递增

如果你需要所有作者选择从1开始连续编号(跨学生),可以调整成下面的代码:

function printGlobalIncrementSelections($students, $selections) {
    $globalKey = 1; // 全局递增键的起始值
    foreach ($students as $index => $studentName) {
        echo "=== {$studentName} 的作者选择 ===\n";
        if (isset($selections[$index]) && is_array($selections[$index])) {
            foreach ($selections[$index] as $author) {
                echo "{$globalKey}. {$author}\n";
                $globalKey++; // 每打印一个就自增
            }
        } else {
            echo "该学生没有选择任何作者\n";
        }
        echo "\n";
    }
}

// 调用函数
printGlobalIncrementSelections($student, $selection);

这种方式的输出会是:

=== Jane 的作者选择 ===
1. Mark Twaine
2. E A Poe
3. James Joyce

=== Michelle 的作者选择 ===
4. Charles Dickens
5. Emily Bronte
6. George Orwell

=== Mark 的作者选择 ===
7. Ernest Hemingway
8. F. Scott Fitzgerald
9. John Steinbeck

两个方案都做了容错处理,如果某个学生没有对应的选择数组(比如$selection的长度和$student不匹配),会友好提示而不是报错。你可以根据实际需求选其中一种就行~

内容的提问来源于stack exchange,提问作者Nawaz Ghori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:10:47