array_values递归php [英] array_values recursive php

查看:167
本文介绍了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天全站免登陆