PHP - 在没有eval()的情况下定位多维数组元素

时间:2012-06-27 14:58:37

标签: php multidimensional-array eval

目标是通过custom_format()传递特定的数组元素。

示例:如果$ hierarchy ='4:0:2',则$ data [4] [0] [2] = custom_format($ data [4] [0] [2] )。

有没有人知道如何复制以下代码而不依赖于eval()

当前代码:

$hierarchy = '4:0:2';
$hierarchy = str_replace(':', '][', $hierarchy);
eval("\$data[$hierarchy] = custom_format(\$data[$hierarchy]);");

提前致谢。

2 个答案:

答案 0 :(得分:2)

以下是一个过于冗长而优雅的选项:

class MyArray implements ArrayAccess {
    public function offsetExists($offset) {
        if(!is_array($offset))
            $offset = explode(':', $value);
        $key = array_shift($offset);
        if($key !== NULL) {
            if($this->$key InstanceOf MyArray) {
                return(isset($this->$key[$offset]));
            }
        }
    }
    public function offsetGet($offset) {
        if(!is_array($offset))
            $offset = explode(':', $value);
        $key = array_shift($offset);
        if($key !== NULL) {
            if($this->$key InstanceOf MyArray) {
                return($this->$key[$offset]);
            }
        }
    }
    public function offsetSet($offset, $value) {
        if(!is_array($offset))
            $offset = explode(':', $value);
        $key = array_shift($offset);
        if($key !== NULL) {
            if(!($this->$key InstanceOf MyArray)) {
                $this->$key = new MyArray;
            }
            $this->$key[$offset] = $value;
        }
    }
    public function offsetUnset($offset) {
        if(!is_array($offset))
            $offset = explode(':', $value);
        $key = array_shift($offset);
        if($key !== NULL) {
            if($this->$key InstanceOf MyArray) {
                return(unset($this->$key[$offset]));
            }
            if(count($offset) == 0) {
                return(unset($this->$key));
            }
        }
    }
}

这确实意味着在需要这种数组行为的任何地方使用MyArray,并且可能创建一个静态方法,递归地转换数组,并将子数组子化为MyArray对象,以便它们能够一致地响应此行为。

一个具体的例子是需要更改offsetGet方法,检查$ value是否为array,然后根据需要使用转换函数将其转换为MyArray访问其元素。

答案 1 :(得分:0)

这样的事情怎么样:

<?php
$hierarchy = '4:0:2';
list($a,$b,$c) = explode(':',$hierarchy);
echo $data[$a][$b][$c];
?>