Php json_encode将我的数组更改为stdClass对象,这正常吗?
我有以下代码:Php json_encode将我的数组更改为stdClass对象,这正常吗?,php,json,Php,Json,我有以下代码: <?php $array = array ( array ('pcs'=>'23', 'kg'=>'3'), array ('pcs'=>'24', 'kg'=>'4'), array ('pcs'=>'25', 'kg'=>'5')); echo '<pre>'; print_r($array); $array = json_encode($arra
<?php
$array = array ( array ('pcs'=>'23', 'kg'=>'3'),
array ('pcs'=>'24', 'kg'=>'4'),
array ('pcs'=>'25', 'kg'=>'5'));
echo '<pre>';
print_r($array);
$array = json_encode($array);
echo $array;
$array = json_decode($array);
echo '<pre>';
print_r($array);
?>
为什么我的数组变成了stdClass对象?我仍然可以像处理数组一样处理stdClass对象吗
更新:我在尝试回显ing$array[0]['pcs']
时遇到此错误:
$array = json_decode($array, true);
echo $array[0]['pcs'];
echo $array[0]['kg'];
“问题”与我们没有任何共同之处,而是与我们有共同之处
这将返回一个数组:
$array=json\u decode($array,true)代码>这是标准的php行为json_decode()
将传入数据转换为类stdClass
的对象数组
您仍然可以访问所有元素,但必须执行更多操作OOP:
$array = json_decode($array,true);
如果希望json\u decode()
再现初始数组,请使用函数的第二个选项:
$array = json_decode($array,TRUE); // use second param as TRUE in your code.
这正常吗
Yes,因为json\u decode
基本上返回一个对象,并且由于没有指定第二个参数,它应该返回一个对象而不是数组
如果为TRUE,则返回的对象将转换为关联数组
所以要让它返回一个数组,就是让第二个参数等于true
<?php
$json = '{"test":"test","test2":"test2"}'; // json string
echo "<pre>";
print_r(json_decode($json)); // without using second param
?>
从:
json_decode()用于解码json
字符串:
在json_decode()
中使用第二个参数作为TRUE
时:
返回的对象将转换为关联数组
您的解决方案:
stdClass Object
(
[test] => test
[test2] => test2
)
<?php
$json = '{"test":"test","test2":"test2"}';
echo "<pre>";
print_r(json_decode($json,TRUE)); // with second param true
?>
一些基本的理解示例:
stdClass Object
(
[test] => test
[test2] => test2
)
<?php
$json = '{"test":"test","test2":"test2"}';
echo "<pre>";
print_r(json_decode($json,TRUE)); // with second param true
?>
示例1:
stdClass Object
(
[test] => test
[test2] => test2
)
<?php
$json = '{"test":"test","test2":"test2"}';
echo "<pre>";
print_r(json_decode($json,TRUE)); // with second param true
?>
示例2:
stdClass Object
(
[test] => test
[test2] => test2
)
<?php
$json = '{"test":"test","test2":"test2"}';
echo "<pre>";
print_r(json_decode($json,TRUE)); // with second param true
?>
如果您喜欢数组语法和结构,您可以或多或少地遍历stdClass对象,就像遍历数组一样,使用json\u decode($data,true)代码>强制输出为数组我建议您阅读手册。