【问题标题】:Getting an array result from json_decode从 json_decode 获取数组结果
【发布时间】:2011-07-09 17:19:51
【问题描述】:

我如何从json_decode() 获得一个数组?

我有一个这样的数组:

$array = array(
  'mod_status' => 'yes',
  'mod_newsnum' => 5
);

我把它保存在数据库中,比如 JSON 编码:

{"mod_status":"yes","mod_newsnum":5}

现在我想再次从数据库中获取数组。但是当我使用时:

$decode = json_decode($dbresult);

我明白了:

stdClass Object (
  [mod_status] => yes
  [mod_newsnum] => 5
)

而不是数组。如何获取数组而不是对象?

【问题讨论】:

标签: php arrays json


【解决方案1】:

根据http://in3.php.net/json_decode

$decode = json_decode($dbresult, TRUE);

【讨论】:

  • +1 用于使用“read the fine manual”的缩写。 ;)
  • F 代表该死的“F”字:P
  • 哎呀!抱歉,那条评论比较轻松:(
【解决方案2】:

如果您只在 PHP 中使用该数据,我建议您改用 serializeunserialize,否则您将永远无法区分对象和关联数组,因为在编码为 JSON 时会丢失对象类信息。

<?php
class myClass{// this information will be lost when JSON encoding //
    public function myMethod(){
        echo 'Hello there!';
    }
}
$x = array('a'=>1, 'b'=>2);
$y = new myClass;
$y->a = 1;
$y->b = 2;
echo json_encode($x), "\n", json_encode($y); // identical
echo "\n", serialize($x), "\n", serialize($y); // not identical
?>

Run it.

【讨论】:

  • 不回答问题:应该改为评论。
  • @Mark 它提出了一个可能更好的替代方案。我认为这些答案也是有效的。我在最新的编辑中添加了更多参数。
【解决方案3】:

设置json_decode的第二个参数为true强制关联数组:

$decode = json_decode($dbresult, true);

【讨论】:

  • 这应该是真正的答案。对我更有帮助。
【解决方案4】:
$decode = json_decode($dbresult, true);

或者

$decode = (array)json_decode($dbresult);

【讨论】:

    【解决方案5】:

    json_decode 的对象结果转换为数组可能会产生意想不到的结果(并导致头痛)。因此,建议使用json_decode($json, true) 而不是(array)json_decode($json)。这是一个例子:

    破碎:

    <?php
    
    $json = '{"14":"29","15":"30"}';
    $data = json_decode($json);
    $data = (array)$data;
    
    // Array ( [14] => 29 [15] => 30 )
    print_r($data);
    
    // Array ( [0] => 14 [1] => 15 )
    print_r(array_keys($data));
    
    // all of these fail
    echo $data["14"];
    echo $data[14];
    echo $data['14'];
    
    // this also fails
    foreach(array_keys($data) as $key) {
        echo $data[$key];
    }
    

    工作:

    <?php
    
    $json = '{"14":"29","15":"30"}';
    $data = json_decode($json, true);
    
    // Array ( [14] => 29 [15] => 30 )
    print_r($data);
    
    // Array ( [0] => 14 [1] => 15 )
    print_r(array_keys($data));
    
    // all of these work
    echo $data["14"];
    echo $data[14];
    echo $data['14'];
    
    // this also works
    foreach(array_keys($data) as $key) {
        echo $data[$key];
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 1970-01-01
      • 2017-09-30
      • 2022-01-09
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多