change a key of a single element array

前端 未结 2 448
Happy的楠姐
Happy的楠姐 2021-01-17 08:38

I have an array tree from a database, I want to change the key of a child element in this case the second array \'eric\'=>array into integer \'0\'=>array as follow :

<
相关标签:
2条回答
  • 2021-01-17 08:55

    can you change your code for this input:

    Array
    (
        [0] => Array
            (
                [text] => paris
                [nodes] => Array
                    (
                        [jacque] => Array
                            (
                                [text] => jacque
                                [nodes] => Array
                                    (
                                        [0] => 32.png
                                    )
                            )
    
                        [anis] => Array
                            (
                                [text] => anis
                                [nodes] => Array
                                    (
                                        [0] => 5384a97ee9d6b (2).pd
                                    )
                            )
                    )
            )
    
        [1] => Array
            (
                [text] => london
                [nodes] => Array
                    (
                        [dodo] => Array
                            (
                                [text] => dodo
                                [nodes] => Array
                                    (
                                        [0] => 148782.svg
                                        [1] => 333.png
                                    )
    
                            )
    
                        [sd] => Array
                            (
                                [text] => sd
                                [nodes] => Array
                                    (
                                        [0] => 1014-favicon.ico
                                    )
    
                            )
    
                       )
            )
    )
    
    0 讨论(0)
  • 2021-01-17 09:06

    To change all of the child keys to numeric values, you can simply just use array_values()

    Live Demo

    for($i = 0; $i <= count($data) -1; $i++) { # This loops through each country
        $data[$i]['nodes'] = array_map(function($node) { # This preserves the parent text value
            return array_values($node); # [0] => Paris, [1] => array(...)
        }, $data[$i]['nodes']);
    }
    

    Output

    [ ... => [ text => Paris, nodes => [ 0 => Paris, 1 => [ ... ] ] ... ] ... ]
    
    0 讨论(0)
提交回复
热议问题