-1

在 PHP 中使用 foreach 循环我想将 id 添加到以下对象...

$array_before

Array
(
    [1111] => Array
        (
            [Name] => Name A
            [Subcats] => Array
                (
                    [11111] => Array
                        (
                            [Name] => Name A.1
                        )
                    [11112] => Array
                        (
                            [Name] => Name A.2
                        )
                )
        )
    [2222] => Array
        (
            [Name] => Name B
            [Subcats] => Array
                (
                    [22221] => Array
                        (
                            [Name] => Name B.1
                        )
                    [22222] => Array
                        (
                            [Name] => Name B.2
                        )
                )
        )
)

...所以它看起来类似于以下内容:

$array_after

Array
(
    [1111] => Array
        (
            [Id] => 1
            [Name] => Name A
            [Subcats] => Array
                (
                    [11111] => Array
                        (
                            [Id] => 1
                            [Name] => Name A.1
                        )
                    [11112] => Array
                        (
                            [Id] => 2                       
                            [Name] => Name A.2
                        )
                    [11113] => Array
                        (
                            [Id] => 3                       
                            [Name] => Name A.2
                        )                       
                )
        )
    [2222] => Array
        (
                    [Id] => 2
                    [Name] => Name B
            [Subcats] => Array
                (
                    [22221] => Array
                        (
                            [Id] => 1                       
                            [Name] => Name B.1
                        )
                    [22222] => Array
                        (
                            [Id] => 2                       
                            [Name] => Name B.2
                        )
                )
        )
)

有人能指出我正确的方向吗?

谢谢, LG

4

1 回答 1

6

试试这个:

$id = 0;
array_walk($array,function(&$a) use (&$id) {$a['id'] = ++$id;});

这将修改原始数组以添加 ID,而不是创建一个新数组。

于 2013-01-16T16:19:03.503 回答