PHP动态数组路径访问 [英] PHP dynamic array path access

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

问题描述

我可以轻松地在会话数组中的子数组中读写。

I can easily write to and read from a sub-array in the session array.

$_SESSION['a']['b']['c']['value']=123;
$val=$_SESSION['a']['b']['c']['value'];

我希望可以定义它,而不是硬编码写入值的位置通过字符串或其他方式。以下内容显然不起作用,但希望可以更好地解释其意图。

Instead of hard coding the "location" where the value is written, I would like it to be definable via a string or some other way. The following will obviously not work, but hopefully will better explain the intent.

$prefix="['a']['b']['c']";  //defined in config page, etc
$_SESSION.$prefix.['value']=123;
$val=$_SESSION.$prefix.['value'];

如何实现?

推荐答案

PropertyAccess



对于此类任务,有一个出色的Symfony组件,名为 PropertyAccess 。您可以按以下方式使用它:

PropertyAccess

There is an excellent Symfony component for such tasks, named PropertyAccess. You can use it as follows:

$persons = array('a' => array('b' => 5.7));
$accessor = PropertyAccess::createPropertyAccessor();
echo $accessor->getValue($persons, '[a][b]'); // 5.7

您可以按照文档中的说明使用Composer安装它,也可以直接从 GitHub

You can install it using Composer as described in docs or fetch directly from GitHub.

这是一个完整的解决方案,它的确给我留下了深刻的印象……但是它有效!检查下面的代码, assert()演示用法:

This is a complete solution, I'm really impressed that it works... but it works! Check the code below, assert()'s demonstrate the usage:

<?php
function arrayPropertyPathGet(array $arr, $path) {
    $parts = explode('.', $path);
    $ret = $arr;
    foreach($parts as $part) {
        $ret = $ret[$part];
        }
    return $ret;
    }

function arrayPropertyPathSet(array &$arr, $path, $value) {
    $parts = explode('.', $path);
    $tmp = &$arr;
    foreach($parts as $part) {
        if(!isset($tmp[$part])) { return false; }
        $tmp = &$tmp[$part];
        }
    $tmp = $value;
    return true;
    }

$test = array('a' => array('b' => 'value'));

assert('value' === arrayPropertyPathGet($test, 'a.b'));
assert(true === arrayPropertyPathSet($test, 'a.b', 'other'));
assert('other' === arrayPropertyPathGet($test, 'a.b'));



侧面注



从理论上讲请注意(不要将其用于学习目的),您可以尝试 eval(),例如:

eval("$value = $persons['a']['b']");

这篇关于PHP动态数组路径访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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