array_walk_recursive

array_walk_recursive(array|object &$array, callable $callback, mixed $arg = null): true

递归遍历嵌套数组、只对叶子标量回调——与 array_walk(只走一层)对照:深度差异决定用途;各语言无直接对应,普遍手写递归或树形枚举。

C C23

C23
#include <stdio.h>

/* C 没有嵌套数组:用结构体显式建模叶子树 */
typedef struct Node {
    int leaf;
    int value;
    struct Node *children[3];
    int nchild;
} Node;

static void walk_leaves(const Node *n, int *out, int *count) {
    if (n->leaf) {
        out[(*count)++] = n->value;
        return;
    }
    for (int i = 0; i < n->nchild; i++)
        walk_leaves(n->children[i], out, count);
}

int main(void) {
    Node l1 = {1, 1, {0}, 0}, l2 = {1, 2, {0}, 0}, l3 = {1, 3, {0}, 0};
    Node l4 = {1, 4, {0}, 0}, l5 = {1, 5, {0}, 0}, l6 = {1, 6, {0}, 0};
    Node n23 = {0, 0, {&l2, &l3}, 2};
    Node n56 = {0, 0, {&l5, &l6}, 2};
    Node n456 = {0, 0, {&l4, &n56}, 2};
    Node root = {0, 0, {&l1, &n23, &n456}, 3};
    int leaves[16] = {0};
    int count = 0;
    walk_leaves(&root, leaves, &count);
    for (int i = 0; i < count; i++)
        printf("%d%s", leaves[i], i + 1 < count ? "," : "\n");
    printf("count: %d\n", count);
    return 0;
}
输出
1,2,3,4,5,6
count: 6

C++ C++26

C++26
#include <iostream>
#include <variant>
#include <vector>

// C++ 同样没有嵌套数组:用递归 variant 建模叶子与节点
struct Node;
using Tree = std::variant<int, std::vector<Node>>;
struct Node { Tree value; };

static Node leaf(int v) { Node n; n.value = Tree(v); return n; }
static Node node(std::vector<Node> children) { Node n; n.value = Tree(children); return n; }

static void walk_leaves(const Tree &t, std::vector<int> &out) {
    if (auto v = std::get_if<int>(&t)) {
        out.push_back(*v);
    } else {
        for (const Node &child : std::get<std::vector<Node>>(t))
            walk_leaves(child.value, out);
    }
}

int main() {
    std::vector<Node> tree{
        leaf(1),
        node({leaf(2), leaf(3)}),
        node({leaf(4), node({leaf(5), leaf(6)})}),
    };
    std::vector<int> leaves;
    walk_leaves(Tree(tree), leaves);
    for (size_t i = 0; i < leaves.size(); i++)
        std::cout << leaves[i] << (i + 1 < leaves.size() ? "," : "\n");
    std::cout << "count: " << leaves.size() << "\n";
    return 0;
}
输出
1,2,3,4,5,6
count: 6

C# v11.0.100

v11.0.100
// 在 List<object> 上手写递归遍历
static void WalkLeaves(object node, List<int> leaves) {
    if (node is List<object> list) {
        foreach (object child in list) WalkLeaves(child, leaves);
    } else if (node is int i) {
        leaves.Add(i);
    }
}

var tree = new List<object> { 1, new List<object> { 2, 3 },
    new List<object> { 4, new List<object> { 5, 6 } } };
var leaves = new List<int>();
WalkLeaves(tree, leaves);
Console.WriteLine(string.Join(",", leaves));
Console.WriteLine($"count: {leaves.Count}");
输出
1,2,3,4,5,6
count: 6

Go v1.27.4

v1.27.4
package main

import "fmt"

// 在 []interface{} 上手写递归遍历
func walkLeaves(node interface{}, visit func(int)) {
	switch v := node.(type) {
	case []interface{}:
		for _, child := range v {
			walkLeaves(child, visit)
		}
	case int:
		visit(v)
	}
}

func main() {
	tree := []interface{}{1, []interface{}{2, 3},
		[]interface{}{4, []interface{}{5, 6}}}
	leaves := []int{}
	walkLeaves(tree, func(v int) { leaves = append(leaves, v) })
	for i, v := range leaves {
		if i > 0 {
			fmt.Print(",")
		}
		fmt.Print(v)
	}
	fmt.Println()
	fmt.Printf("count: %d\n", len(leaves))
}
输出
1,2,3,4,5,6
count: 6

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;

public class Main {
    // 在 List<Object> 上手写递归遍历
    static void walkLeaves(Object node, List<Integer> out) {
        if (node instanceof List<?> list) {
            for (Object child : list) walkLeaves(child, out);
        } else if (node instanceof Integer i) {
            out.add(i);
        }
    }

    public static void main(String[] args) {
        List<Object> tree = new ArrayList<>(List.of(1,
                new ArrayList<>(List.of(2, 3)),
                new ArrayList<>(List.of(4, new ArrayList<>(List.of(5, 6))))));
        List<Integer> leaves = new ArrayList<>();
        walkLeaves(tree, leaves);
        System.out.println(leaves.toString().replace("[", "").replace("]", "").replace(" ", ""));
        System.out.println("count: " + leaves.size());
    }
}
输出
1,2,3,4,5,6
count: 6

JavaScript v26.13.1

v26.13.1
// 手写递归遍历:访问每个标量叶子
function walkLeaves(node, visit) {
  if (Array.isArray(node)) {
    for (const child of node) walkLeaves(child, visit);
  } else {
    visit(node);
  }
}
const tree = [1, [2, 3], [4, [5, 6]]];
const leaves = [];
walkLeaves(tree, (v) => leaves.push(v));
console.log(leaves.join(","));
console.log("count: " + leaves.length);
输出
1,2,3,4,5,6
count: 6

PHP v8.6.0

v8.6.0
// 只走叶子:任意深度的标量值
$tree = [1, [2, 3], [4, [5, 6]]];
$leaves = [];
array_walk_recursive($tree, function ($v, $k) use (&$leaves) {
    $leaves[] = $k . ":" . $v;
});
echo implode(",", $leaves), "\n";
// 对照:array_walk 只走外层(3 个元素)
$depth1 = 0;
array_walk($tree, function ($v) use (&$depth1) { $depth1++; });
echo $depth1, "\n";
输出
0:1,0:2,1:3,0:4,0:5,1:6
3

Python v3.15.2

v3.15.2
# 手写递归遍历:访问每个标量叶子
def walk_leaves(node, visit):
    if isinstance(node, list):
        for child in node:
            walk_leaves(child, visit)
    else:
        visit(node)

tree = [1, [2, 3], [4, [5, 6]]]
leaves = []
walk_leaves(tree, leaves.append)
print(",".join(str(v) for v in leaves))
print(f"count: {len(leaves)}")
输出
1,2,3,4,5,6
count: 6

Rust v1.99.1

v1.99.1
// 用递归 enum 建模树,再遍历叶子
#[derive(Debug)]
enum Tree {
    Leaf(i32),
    Node(Vec<Tree>),
}

fn walk_leaves(t: &Tree, out: &mut Vec<i32>) {
    match t {
        Tree::Leaf(v) => out.push(*v),
        Tree::Node(children) => {
            for c in children {
                walk_leaves(c, out);
            }
        }
    }
}

fn main() {
    let tree = Tree::Node(vec![
        Tree::Leaf(1),
        Tree::Node(vec![Tree::Leaf(2), Tree::Leaf(3)]),
        Tree::Node(vec![Tree::Leaf(4),
            Tree::Node(vec![Tree::Leaf(5), Tree::Leaf(6)])]),
    ]);
    let mut leaves = Vec::new();
    walk_leaves(&tree, &mut leaves);
    let strs: Vec<String> = leaves.iter().map(|v| v.to_string()).collect();
    println!("{}", strs.join(","));
    println!("count: {}", leaves.len());
}
输出
1,2,3,4,5,6
count: 6

TypeScript v26.13.1

v26.13.1
// 手写递归遍历:访问每个标量叶子
function walkLeaves(node: number | any[], visit: (v: number) => void): void {
  if (Array.isArray(node)) {
    for (const child of node) walkLeaves(child, visit);
  } else {
    visit(node);
  }
}
const tree: number | any[] = [1, [2, 3], [4, [5, 6]]];
const leaves: number[] = [];
walkLeaves(tree, (v) => leaves.push(v));
console.log(leaves.join(","));
console.log("count: " + leaves.length);
输出
1,2,3,4,5,6
count: 6

语言差异说明

C:无嵌套数组——结构体叶子树 + 显式递归(示例);这种手动建模正是「递归遍历」的本质。

C++:递归 variant 建模(示例);std::variant<int, vector<Node>> 表达「叶子或子节点列表」的类型级直觉,比 C 的裸结构体安全。

C#:List<object> + 模式匹配递归(示例);真正生产中建议定义强类型树,object 混合仅演示 PHP 数组的动态形态。

Go:[]interface{} + type switch 递归(示例);interface{} 混合正是 PHP 数组异构性的 Go 对应物,代价是运行时断言。

Java:List<Object> + instanceof 模式匹配递归(示例);泛型擦除让 List.of 混装 int 与 List 需 Object 类型。

JavaScript:Array.isArray 判定 + 递归(示例);数组即语言内建嵌套结构,无需建模。

PHP:array_walk_recursive 只对叶子(标量)回调、嵌套数组自身不触发回调;键值回调收的是各自数组内的键(示例里内层数组的键从 0 重计);与 array_walk 的分工:一层就地修改 vs 全深度叶子访问;回调里改值须按引用 function (&$v)。

Python:isinstance(list) 判定 + 递归(示例);列表推导 flatten 到固定深度([x for sub in tree for x in (sub if isinstance(sub, list) else [sub])])只能解一层,任意深度仍须递归。

Rust:递归 enum 建模(示例);Leaf/Node 的 match 递归把「深度未知」编码进类型系统,比动态检查更根本。

TypeScript:同 JavaScript 递归(示例);number | any[] 联合类型把叶子/节点写进签名。