php - 在 PHP 的关联数组中是否有类似 keypath 的东西?

标签 php key associative-array

我想像这样剖析一个数组:

[
    "ID",
    "UUID",
    "pushNotifications.sent",
    "campaigns.boundDate",
    "campaigns.endDate",
    "campaigns.pushMessages.sentDate",
    "pushNotifications.tapped"
]

格式如下:

{
    "ID" : 1,
    "UUID" : 1,
    "pushNotifications" : 
        {
            "sent" : 1,
            "tapped" : 1
        },
    "campaigns" :
        {
            "boundDate" : 1,
            "endDate" : 1,
            "pushMessages" :
                {
                    "endDate" : 1
                }  
        }
}

如果我能以类似键路径的方式在关联数组上设置一个值,那就太好了:

//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;

//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;

如何在 PHP 中执行此操作?

最佳答案

你可以使用:

$array = [
        "ID",
        "UUID",
        "pushNotifications.sent",
        "campaigns.boundDate",
        "campaigns.endDate",
        "campaigns.pushMessages.sentDate",
        "pushNotifications.tapped"
];

// Build Data
$data = array();
foreach($array as $v) {
    setValue($data, $v, 1);
}

// Get Value
echo getValue($data, "campaigns.pushMessages.sentDate"); // output 1

使用的函数

function setValue(array &$data, $path, $value) {
    $temp = &$data;
    foreach(explode(".", $path) as $key) {
        $temp = &$temp[$key];
    }
    $temp = $value;
}

function getValue($data, $path) {
    $temp = $data;
    foreach(explode(".", $path) as $ndx) {
        $temp = isset($temp[$ndx]) ? $temp[$ndx] : null;
    }
    return $temp;
}

关于php - 在 PHP 的关联数组中是否有类似 keypath 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389168/

相关文章:

php - 使用javascript循环使用php动态创建的控件

php - Nginx + PHP、Node.js 和 jQuery 设置

PHP 从字符串中删除查询字符串变量

json - Kotlin 没有将 "is"作为 json key 的开始

javascript - JS中关联数组和对象的区别

c# - formcollection如何访问html表单关联数组

php - 将录制的音频从Android SD卡发送到外部文件夹

MySQL查询以根据两列的值获取所有重复项

PHP,传递包含数组键的字符串以查找数组值

arrays - 当键包含引号时取消关联 bash 数组中的值