array_values 递归 php [英] array_values recursive php

查看:29
本文介绍了array_values 递归 php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的数组:

Let's say I have an array like this:

Array
(
    [id] => 45
    [name] => john
    [children] => Array
    (
        [45] => Array
            (
                [id] => 45
                [name] => steph
                [children] => Array
                    (
                        [56] => Array
                            (
                                [id] => 56
                                [name] => maria
                                [children] => Array
                                    (
                                        [60] => Array
                                            (
                                                [id] => 60
                                                [name] => thomas
                                            )

                                        [61] => Array
                                            (
                                                [id] => 61
                                                [name] => michelle
                                            )

                                    )
                            )

                        [57] => Array
                            (
                                [id] => 57
                                [name] => luis
                            )

                     )

            )

    )

)

我想要做的是将带有键 children 的数组的键重置为 0、1、2、3 等,而不是 45、56 或 57.

What I'm trying to do is to reset the keys of the array with keys children to 0, 1, 2, 3, and so on, instead of 45, 56, or 57.

我尝试了类似的东西:

function array_values_recursive($arr)
{
    foreach ($arr as $key => $value)
    {
        if(is_array($value))
        {
            $arr[$key] = array_values($value);
            $this->array_values_recursive($value);
        }
    }

    return $arr;
}

但是那只重置了第一个子数组的键(键为 45 的那个)

But that reset only the key of the first children array (the one with key 45)

推荐答案

您使用了递归方法,但没有分配函数调用的返回值 $this->array_values_recursive($value); 任何地方.当您在循环中修改 $arr 时,第一级有效.由于上述原因,任何进一步的级别都不再起作用.

You use a recursive approach but you do not assign the return value of the function call $this->array_values_recursive($value); anywhere. The first level works, as you modify $arr in the loop. Any further level does not work anymore for mentioned reasons.

如果您想保留您的功能,请按如下方式更改(未经测试):

If you want to keep your function, change it as follows (untested):

function array_values_recursive($arr)
{
  foreach ($arr as $key => $value)
  {
    if (is_array($value))
    {
      $arr[$key] = $this->array_values_recursive($value);
    }
  }

  if (isset($arr['children']))
  {
    $arr['children'] = array_values($arr['children']);
  }

  return $arr;
}

这篇关于array_values 递归 php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆