Anjali
Anjali

Reputation: 43

How to convert an array to JSON?

I am having array in this format.

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

    [1] => Array
        (
            [0] => Anjali
            [1] => [email protected]
            [2] => 9945587526
        )

)

and i am looking a json

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

Upvotes: 1

Views: 78

Answers (4)

Satish Sharma
Satish Sharma

Reputation: 9625

<?php

  $your_array = array(
                      0 => array(
                                    0 => "your name",
                                    1 => "your email",
                                    2 => "your mobile"
                                ),
                      1 => array(
                                    0 => "Anjali",
                                    1 => "[email protected]",
                                    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":"[email protected]","3":"999999999"}

WORKING DEMO

Upvotes: 1

Mark Miller
Mark Miller

Reputation: 7447

You need json_encode, but to include the keys of the array, you need to set the JSON_FORCE_OBJECT option (available in PHP >= 5.3.0).

echo json_encode($arr, JSON_FORCE_OBJECT);

See demo

Upvotes: 3

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

You are looking for json_encode

Returns a string containing the JSON representation of value.

echo json_encode($array);

Also json_encode is available in php > 5.2.0

Also you may try this:

$json = array2json($data);

Also note that Array in JSON are indexed array only and PHP Associatives array are objects in JSON

Upvotes: 3

Manwal
Manwal

Reputation: 23816

Use function json_encode

Example:

echo json_encode($your_array);

Upvotes: 1

Related Questions