Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php json_encode将我的数组更改为stdClass对象,这正常吗?_Php_Json - Fatal编程技术网

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)强制输出为数组我建议您阅读手册。