如何将php数组转换为JSON?

时间:2014-02-07 19:08:01

标签: php arrays json

我有以下数组,我想将其转换为json格式,所以请帮助我。

<?php

   $txt=array("apple","orange","papaya");

   json_encode($txt);

?>

输出: - [“apple”,“orange”,“papaya”]

But i want the output in the following format

[{"fruit":{"1":"apple","2":"orange","3":"papaya"}}]

请帮帮我,我使用了json_encode,但我没有得到预期的结果。

那么,请建议我,可能的解决方案是什么?

先谢谢!!!

1 个答案:

答案 0 :(得分:0)

只需这样做:

<?php
   $txt=array(
           array("fruit"=>
                       array(1=> "apple",
                             2=>"orange",
                             3=>"papaya")
                   )
   );

   echo json_encode($txt);

?>

<强>输出:

[{"fruit":{"1":"apple","2":"orange","3":"papaya"}}]

demo