如何在PHP中动态设置数组键 [英] How to dynamically set array keys in php

查看:121
本文介绍了如何在PHP中动态设置数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于对数据进行排序的逻辑,但是根据用户输入的不同,数据的分组方式也不同.现在,我有五个包含相同逻辑但不同分组的不同功能.有没有一种方法可以组合这些功能并动态设置一个可以正确分组的值.在函数中,这些分配正在发生

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 same logic but different groupings. Is there a way to combine these functions and dynamically set a value that will group properly. Within the function these assignments are happening

例如,有时我仅通过以下方式存储计算:

For example, sometimes I store the calculations simply by:

$calcs[$meter['UnitType']['name']] = ...

但其他时候需要更具体的分组:

but other times need a more specific grouping:

$calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] =...

如您所见,有时将其存储在一个多维数组中,有时则不存储.我一直在尝试使用eval(),但没有成功(不确定那是正确的方法).将数据存储在临时变量中并不会真正节省多少,因为有很多嵌套循环和if语句,因此必须在多个位置重复数组.

As you can see sometimes it is stored in a multidiminesional array and other times not. I have been trying to use eval() but without success (not sure that is the correct approach). Storing the data in a temporary variable does not really save much because there are many nested loops and if statements so the array would have to be repeated in multiple places.

编辑

我希望以下示例可以更好地说明我的问题.显然,它是一个愚蠢的版本:

I hope the following example explains my problem better. It is obviously a dumbed down version:

if(){
     $calcs[$meter['UnitType']['name']] = $data;
} else {
    while () {
       $calcs[$meter['UnitType']['name']] = $data;
    }
} 

现在可以使用相同的逻辑,但是将其存储在不同的键中:

Now the same logic can be used but for storing it in different keys:

if(){
     $calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] = $data;
} else {
    while () {
       $calcs[$meter['Resource']['name']][$meter['UnitType']['name']][date('Y-m',$start)] = $data;
    }
} 

是否有一种方法可以提取$ calc []数组中的键,以便我可以使用一个函数,而不用多个具有不同数组键的函数?

Is there a way to abstract out the keys in the $calc[] array so that I can have one function instead of having multiple functions with different array keys?

推荐答案

这是我编写的用于在数组或对象上设置深层嵌套成员的函数:

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;
}

使用示例数据:

$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);

结果显示如下:

Array
(
    [resource1] => Array
        (
            [unit1] => Array
                (
                    [2017-10] => value1
                )

            [unit2] => Array
                (
                    [2017-11] => value2
                )

        )

    [resource2] => Array
        (
            [unit1] => Array
                (
                    [2017-10] => value3
                )

        )

)

dict_set()的第二个参数是点符号中的$path字符串.您可以使用在零件之间带有句点定界符的动态键来构建它.该函数可用于数组和对象.

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.

通过将[]用作$path的元素,它也可以将增量成员追加到深层嵌套的数组中.例如:parent.child.child.[]

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

这篇关于如何在PHP中动态设置数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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