How to dynamically set array keys in php

前端 未结 6 2490
星月不相逢
星月不相逢 2021-02-20 18:48

I have some logic that is being used to sort data but depending on the user input the data is grouped differently. Right now I have five different functions that contain the sa

6条回答
  •  一个人的身影
    2021-02-20 19:32

    Here's a function I wrote for setting deeply nested members on arrays or objects:

    function dict_set($var, $path, $val) {
        if(empty($var))
            $var = is_array($var) ? array() : new stdClass();
    
        $parts = explode('.', $path);
        $ptr =& $var;
    
        if(is_array($parts))
        foreach($parts as $part) {
            if('[]' == $part) {
                if(is_array($ptr))
                    $ptr =& $ptr[];
    
            } elseif(is_array($ptr)) {
                if(!isset($ptr[$part]))
                    $ptr[$part] = array();
    
                $ptr =& $ptr[$part];
    
            } elseif(is_object($ptr)) {
                if(!isset($ptr->$part))
                    $ptr->$part = array();
    
                $ptr =& $ptr->$part;
            }
        }
    
        $ptr = $val;
    
        return $var;
    }
    

    Using your example data:

    $array = [];
    
    $array = dict_set($array, 'resource1.unit1.2017-10', 'value1');
    $array = dict_set($array, 'resource1.unit2.2017-11', 'value2');
    $array = dict_set($array, 'resource2.unit1.2017-10', 'value3');
    
    print_r($array);
    

    Results in output like:

    Array
    (
        [resource1] => Array
            (
                [unit1] => Array
                    (
                        [2017-10] => value1
                    )
    
                [unit2] => Array
                    (
                        [2017-11] => value2
                    )
    
            )
    
        [resource2] => Array
            (
                [unit1] => Array
                    (
                        [2017-10] => value3
                    )
    
            )
    
    )
    

    The second argument to dict_set() is a $path string in dot-notation. You can build this using dynamic keys with period delimiters between the parts. The function works with arrays and objects.

    It can also append incremental members to deeply nested array by using [] as an element of the $path. For instance: parent.child.child.[]

提交回复
热议问题