【问题标题】:How to remove the keys from a multi-dimensional associative array?如何从多维关联数组中删除键?
【发布时间】:2021-02-06 11:24:19
【问题描述】:

我有一个关联数组,格式如下:

array (
  'Shopping and fashion' => 
  array (
    'childData' => 
    array (
      'Beauty' => 
      array (
        'childData' => 
        array (
          'Cosmetics' => 
          array (
            'id' => '6002839660079',
            'name' => 'Cosmetics',
            'parentName' => 'Beauty',
          ),
          'Tattoos' => 
          array (
            'id' => '6003025268985',
            'name' => 'Tattoos',
            'parentName' => 'Beauty',
          ),),))))

我想从数组中删除键。 为此,我正在使用:

array_values($my_data)

但是,这仅适用于数组的最顶层,在本例中为“购物和时尚”。它将其转换为索引 0。 我怎样才能对索引内的每个数组也做同样的事情?

预期输出:

array (
    0 =>
        array (
            'childData' =>
                array (
                    0 =>
                        array (
                            'childData' =>
                                array (
                                    0 =>
                                        array (
                                            'id' => '6002839660079',
                                            'name' => 'Cosmetics',
                                            'parentName' => 'Beauty',
                                        ),
                                    1 =>
                                        array (
                                            'id' => '6003025268985',
                                            'name' => 'Tattoos',
                                            'parentName' => 'Beauty',
                                        ),
                                ),
                            'name' => 'Beauty',
                            'id' => '6002867432822',
                            'parentName' => 'Shopping and fashion',
                        ),)))

我拥有的数组在父级上有许多不同的数组,并且在它们内部有更多的数组,因此使用每个数组都会带来问题,因为“childData”的数量,即父数组中的子数组是不同的。

可以递归吗?

【问题讨论】:

    标签: php arrays multidimensional-array foreach associative-array


    【解决方案1】:

    我不知道内置函数,但也许这个函数会对你有所帮助?

    function array_values_recursive( $array ) {
        $newArray = [];
        foreach ( $array as $key => $value ) {
            if ( is_array( $value ) ) {
                $newArray[] = array_values_recursive( $value );
            } else {
                $newArray[$key] = $value;
            }
        }
        return $newArray;
    }
    

    【讨论】:

    • 接近答案但并不完美。它也使数组中的数据也被索引。例如:``` Cosmetics' => array ('id' => '6002839660079', 'name' => 'Cosmetics', 'parentName' => 'Beauty',) ``` 改为: ``` 数组( 0 => '6002839660079', 1 => '化妆品', 2 => '美容', ) ```
    • 应该是$newArray[] = $value;
    • @nice_dev 但它会返回 return 作为第一个答案。没有钥匙...
    • @PHP_Newbie 使用预期输出编辑您的帖子以避免任何混淆。
    • 是的。 @UrmatZhenaliev 非常感谢你帮助我这个更新对我有用
    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 2018-09-16
    • 2021-04-24
    • 2016-06-16
    • 1970-01-01
    • 2021-05-01
    • 2011-03-04
    • 2010-12-17
    相关资源
    最近更新 更多