【发布时间】:2020-07-22 04:41:04
【问题描述】:
我有一个对象,我必须转换成数组,我使用了 json 编码和 json 解码,但它不能正常工作。
我的对象
$LearningNodesData = '{
0:"5df31",
1:"5df32",
2:"5df33"
}';
我的代码
$LearningNodesData1 =json_decode(json_encode($LearningNodesData,true),true);
echo "<pre>";
print_r($LearningNodesData1);
我的预期输出
[
"5df31",
"5df32",
"5df33"
]
我的输出
{
0:"5df1",
1:"5df2",
2:"5df3"
}
这里有什么问题
更新的代码部分
<?php
$LearningNodesData = '{
"0":"5df31",
"1":"5df32",
"2":"5df33"
}';
echo my_json_decode($LearningNodesData);
function my_json_decode($s) {
$s = str_replace(
array('"', "'"),
array('\"', '"'),
$s
);
$s = preg_replace('/(\w+):/i', '"\1":', $s);
return json_decode(sprintf('{%s}', $s));
}
?>
【问题讨论】:
-
如果你有一个实际有效的 json 字符串,你做错了,先用 true 标志解码,然后编码,所以
encode(decode(string here, true)),你在做另一个绕路 -
@kevin,我用过 $LearningNodesData1 = json_encode(json_decode($LearningNodesData, true));但我收到
null -
如果你期望一个数组,你应该从一个数组开始。