2013-03-31 41 views
0

我目前正在嘗試使用json_decode填充數據的二維數組。但是,它似乎加載正確,但是當我嘗試獲取特定值時,即使它不是,它也會返回null。二維數組返回null與特定值

我2dtestarray.php:

<?php 
class testarray { 

public static $listConfigs; 

public function __construct() { 
    $this->listConfigs = json_decode(file_get_contents('configuration.json'), true); 
} 

public static function getValue($list, $property) { 
    return self::$listConfigs[$list][$property]; 
} 

public function save() { 
    file_put_contents('configuration.json',json_encode($listConfigs)); 
} 
} 
?> 

我testload.php:

<?php 
    require_once("2darraytest.php"); 
    $ta = new testarray(); 

    var_dump($ta->getValue('main', 'canView')); 

    var_dump($ta->listConfigs); 

    $test = json_decode(file_get_contents('configuration.json'), true); 

    var_dump($test); 

    $mainList = $test['main']['canView']; 
    echo $mainList; 
?> 

我configuration.json:

{"main":{"canView":"true"},"secondary":{"canView":"false"}} 

從testload.php輸出:

NULL 
array(2) { ["main"]=> array(1) { ["canView"]=> string(4) "true" } ["secondary"]=> array(1) { ["canView"]=> string(5) "false" } } 
array(2) { ["main"]=> array(1) { ["canView"]=> string(4) "true" } ["secondary"]=> array(1) { ["canView"]=> string(5) "false" } } 
true 

最後,我的問題,這就是爲什麼「var_dump($ ta-> getValue('main','canView'));」返回null並且不是真的像「$ mainList = $ test ['main'] ['canView']; echo $ mainList;」呢?

+0

您正在訪問getValue中的靜態屬性,但訪問'$ ta-> listConfigs'中的實例屬性。構造函數將該值設置爲實例屬性。 – andho

回答

0

您正在訪問getValue靜態屬性:

self::$listConfigs[$list][$property] 

$ta->listConfigs訪問實例屬性。構造函數將該值設置爲實例屬性。

$this->listConfigs = json_decode(file_get_contents('configuration.json'), true); 

因此,這將導致實例同時訪問一個靜態self::$listConfigs和實例屬性$this->listConfigs

嘗試將構造函數更改爲使用靜態屬性。

public function __construct() { 
    self::$listConfigs = json_decode(file_get_contents('configuration.json'), true); 
} 
+0

謝謝!這工作,但它返回「字符串(4)」真「。」有沒有辦法刪除「字符串(4)」部分,或者你可以指向我需要去除的方向? – user1231669

+0

如果你想讓它成爲布爾值(true或false),你應該刪除它周圍的引號(「)。 – andho