2017-06-14 27 views
-3

我有一个PHP类,如下所示:PHP设置和获取多维数组值

Class ArrayStore{ 

static $storage = array(); 

public static set($key, $value){ 
    //set value 
} 

public static get($key){ 
    //return value 
} 

} 

我想怎么使用:

ArrayStore::set('["id"]["name"]["last"]', 'php'); 
ArrayStore::get('["id"]["name"]["last"]'); //should return php 

ArrayStore::set('["multi"]["array"]', 'works'); 
ArrayStore::get('["multi"]["array"]'); //should return works 

让我知道如果有一个更好的方法设置并获得一个有理由的多维数组。

编辑: 我想是这样的:

<?php 
$x = array(1=>'a'); 
$op="\$x"."[1]"; 
$value=eval("return ($op);"); 

echo $value;//prints a. 
?> 
+0

您发布的代码不是OOP,但过程编程(全局变量)伪装下。 PHP已经提供了作为数组工作的['ArrayObject'](http://php.net/manual/en/class.arrayobject.php)类。用它! – axiac

回答

0

从你的逻辑,你可以这样做:

<?php 
class ArrayStore{ 

static $storage = array(); 

public static function set($key, $value){ 
    self::$storage[$key] = $value; 
} 

public static function get($key){ 
    return self::$storage[$key]; 
} 

} 
ArrayStore::set('["id"]["name"]["last"]', 'php'); 
echo ArrayStore::get('["id"]["name"]["last"]'); //should return php 
echo "<br>"; 
ArrayStore::set('["multi"]["array"]', 'works'); 
echo ArrayStore::get('["multi"]["array"]'); //should return works 
+0

它返回预期的输出。然而,它不存储数据像 'array('id'=> array('name'=> array('last'=>'php')))' –