json 编码和解码在 PHP 中不起作用

我有一个对象,我必须转换为数组,我使用了 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));

}

?>


缥缈止盈
浏览 114回答 4
4回答

HUH函数

您的字符串不是有效的 json。有效的 json 是:$LearningNodesData = '{    "0":"5df31",    "1":"5df32",    "2":"5df33"}';

白衣染霜花

您正在尝试对字典进行编码/解码,并且您的预期结果是一个列表。如果您想要的结果是一个列表,那么试试这个!$LearningNodesData&nbsp;=&nbsp;'["5df31","5df32","5df33"]';不是这个$LearningNodesData&nbsp;=&nbsp;'{ &nbsp;&nbsp;&nbsp;&nbsp;0:"5df31", &nbsp;&nbsp;&nbsp;&nbsp;1:"5df32", &nbsp;&nbsp;&nbsp;&nbsp;2:"5df33" }';

LEATH

如果将对象转换为数组,它将始终返回带有键的值&nbsp; &nbsp; $LearningNodesData = '{&nbsp; &nbsp; "0":"5df31",&nbsp; &nbsp; "1":"5df32",&nbsp; &nbsp; "2":"5df33"&nbsp; &nbsp; }';&nbsp; &nbsp;$arr = json_decode($LearningNodesData,true);&nbsp; &nbsp;print_r($arr);&nbsp; //output&nbsp; Array&nbsp; (&nbsp; &nbsp; [0] => 5df31&nbsp; &nbsp; [1] => 5df32&nbsp; &nbsp; [2] => 5df33&nbsp; )在最后的数组中,没有键或有键并不重要(如果它是数字键)。您所需的输出没有密钥,但您将通过它们的索引位置进行访问。如果您不想将其作为数组,可以使用imploade()函数将其转换为逗号格式的字符串echo imploade(',',$arr); //5df31,5df32,5df33

尚方宝剑之说

如果我理解的话,你想回显/打印数组,但没有键?如果是这样:<?php$learningNodesData = '{&nbsp; &nbsp; "0":"5df31",&nbsp; &nbsp; "1":"5df32",&nbsp; &nbsp; "2":"5df33"}';$decodedLearningNodesData = json_decode($learningNodesData, true);$noKeysLearningNodesData = json_encode(array_values($decodedLearningNodesData));print_r($noKeysLearningNodesData);?>将打印出:["5df31","5df32","5df33"]
打开App,查看更多内容
随时随地看视频慕课网APP