繁体   English   中英

从json_decode获取数组结果

[英]Getting an array result from json_decode

如何从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
)

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

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

$decode = json_decode($dbresult, true);

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

$decode = json_decode($dbresult, TRUE);
$decode = json_decode($dbresult, true);

要么

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

json_decode的对象结果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];
}

如果您只在PHP中使用该数据,我建议使用serialize和反unserialize serialize ,否则您将永远无法区分对象和关联数组,因为在编码为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
?>

运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM