如何将数组转换为JSON?

时间:2014-08-04 05:58:23

标签: php json

我有这种格式的数组。

Array
(
    [0] => Array
        (
            [0] => User Name
            [1] => User Email
            [2] => User Mobile
        )

    [1] => Array
        (
            [0] => Anjali
            [1] => anjali@gmail.com
            [2] => 9945587526
        )

)

我正在寻找一个json

{"1":"user name","2":"user email","3":"user mobile"}

4 个答案:

答案 0 :(得分:3)

您正在寻找json_encode

  

返回包含值的JSON表示的字符串。

echo json_encode($array);

php>中也提供了json_encode {} 5.2.0

你也可以试试这个:

$json = array2json($data);

另请注意,JSON中的Array只是索引数组,而PHP Associatives数组是JSON中的对象

答案 1 :(得分:3)

您需要json_encode,但要包含数组的键,您需要设置JSON_FORCE_OBJECT 选项(在PHP> = 5.3.0中可用)

echo json_encode($arr, JSON_FORCE_OBJECT);

See demo

答案 2 :(得分:1)

使用函数json_encode

示例:

echo json_encode($your_array);

答案 3 :(得分:1)

<?php

  $your_array = array(
                      0 => array(
                                    0 => "your name",
                                    1 => "your email",
                                    2 => "your mobile"
                                ),
                      1 => array(
                                    0 => "Anjali",
                                    1 => "Anjali@gmail.com",
                                    2 => "999999999"
                                )            
                   );

foreach($your_array as $key=>$arr)
{
     $arr_temp = array();
     $i=0;
     foreach($arr as $k=>$v)
     {
        $i+=1;
        $arr_temp[$i] = $v;
     } 
     echo json_encode($arr_temp);
     echo "<br/>";
}

?>

OUPUPT:

{"1":"your name","2":"your email","3":"your mobile"}
{"1":"Anjali","2":"Anjali@gmail.com","3":"999999999"}

<强> WORKING DEMO