【问题标题】:2D array returning null with specific value二维数组返回具有特定值的 null
【发布时间】:2013-03-31 04:12:37
【问题描述】:

我目前正在尝试使用 json_decode 用数据填充 2D 数组。但是,它似乎加载正确,但是当我尝试获取特定值时,即使不是,它也会返回 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;
?>

我的配置.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 而不是 true,例如 "$mainList = $test['main']['canView']; echo $mainList;"有吗?

【问题讨论】:

  • 您正在访问 getValue 中的静态属性,但访问的是 $ta-&gt;listConfigs 中的实例属性。构造函数将值设置到实例属性中。

标签: php json


【解决方案1】:

您正在访问getValue 中的静态属性:

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

但访问$ta-&gt;listConfigs 中的实例属性。构造函数将值设置到实例属性中。

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

因此,这会导致实例同时访问静态 self::$listConfigs 和实例属性 $this-&gt;listConfigs

尝试更改构造函数以使用静态属性。

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

【讨论】:

  • 谢谢!这行得通,但它返回“字符串(4)“真”。有没有办法删除“字符串(4)”部分,或者你可以指出我需要去删除它的方向?
  • 如果您希望它是布尔值(true 或 false),您应该删除它周围的引号 (")。
猜你喜欢
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
相关资源
最近更新 更多