php - 用字符串定义数组中的位置

标签 php arrays

我有一个有趣的问题...我正在构建一个 API,用户可以在其中通过字符串指定数组中某个元素的位置。像这样:

$path = "group1.group2.group3.element";

鉴于此字符串,我必须将一些值保存到数组中的正确位置。对于上面的示例,这将是:

$results['group1']['group2']['group3']['element'] = $value;

当然,无论 $path 用户向我抛出什么,代码都必须是通用的。

你会如何解决这个问题?

更新 - 解决方案:使用 ern0(类似于我自己的)和 nikc 的答案作为灵感,这是我决定的解决方案:

// returns reference to node in $collection as referenced by $path. For example:
//   $node =& findnode('dir.subdir', $some_array);
// In this case, $node points to $some_array['dir']['subdir'].
// If you wish to create the node if it doesn't exist, set $force to true 
// (otherwise it throws exception if the node is not found)
function &findnode($path, &$collection, $force = false)
{
    $parts = explode('.', $path);
    $where = &$collection;
    foreach ($parts as $part)
    {
        if (!isset($where[$part]))
        {
            if ($force)
                $where[$part] = array();
            else
                throw new RuntimeException('path not found');
        }
        $where =& $where[$part];
    }
    return $where;
}

$results = array();
$value = '1';
try {
    $bucket =& findnode("group1.group2.group3.element", $results, true);
} catch (Exception $e) {
    // no such path and $force was false
}
$bucket = $value; // read or write value here
var_dump($results);

谢谢大家的回答,这是一个很好的练习! :)

最佳答案

也许,我不太了解 PHP,但我找不到语言元素,它可以将元素插入任何深度的数组。

快速而肮脏的解决方案是eval(),但正如我们所知,它是邪恶的。但是如果你观察输入(点线形式)和结果(数组索引)超过 10 秒,你会问:我们到底为什么要考虑构建自定义深度数组等等,因为它只需要两个简单的*str_replace()*s 将输入转换为结果。

编辑:这是 eval 版本,不要使用它:

 $x = str_replace(".","][",$path); 
 $x = '$result[' . $x . '] = "' . $value . '";'; 
 eval($x);

另一种方法是使用间接方式在不知道深度的情况下爬到树的深处:

$path = "group1.group2.group3.element";
$value = 55;

$x = explode(".",$path);

$result = Array();
$last = &$result;
foreach ($x as $elem) {
    $last[$elem] = Array();
    $last = &$last[$elem];
}
$last = $value;

echo("<pre>$path=$value\n");
print_r($result);

收集数组元素引用供以后完成是一个非常有用的 PHP 功能。

关于php - 用字符串定义数组中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8586309/

相关文章:

c - 如何编写一个使用二维数组生成矩阵的程序?

php - Codeigniter 中的链接不起作用

javascript - Stripe 自定义结帐未发布

php - 测试 Twig 中的变量相等性

PHP $_SERVER ['REMOTE_ADDR' ] 显示 IPv6

PHP - 奇怪的循环结果

java - 快速排序算法的动画

arrays - C - 缓存行和关联

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

arrays - 如何使用术语查询在此数组中搜索?