Elamparithi.P Elamparithi.P - 3 months ago 8
JSON Question

How to change JSON format in PHP?

The below **php **code is for read the json file and get the values from the json and store in php array,

my php code :

$str = file_get_contents('r_json_file/936073.json');


//the format 936073.json format is [["a","b","c"],[1,2,1],[2,3,4]]

$manage = (array) json_decode($str);
print_r($manage);


I got this array format

Array
(
[0] => Array
(
[0] => Cluster
[1] => Cost
[2] => Conversions
[3] => MyColumn
)

[1] => Array
(
[0] => 5
[1] => 2
[2] => 25
[3] => 25
)

[2] => Array
(
[0] => 2
[1] => 48
[2] => 20
[3] => 20
)
)


Values in the array are dynamic(changes as per the input).I need to change the above format as {"key":"value"} this format.

Can any body help me ?

Answer

You can try this

$firstJson = '[["name","email","phone"],["A","abc@mail.com","1234569870"]]';

$decodedFirstJson = json_decode($firstJson);

$createFinalJsonArr = array(array(
        'name' => $decodedFirstJson[1][0],
        'email' => $decodedFirstJson[1][1],
        'phone' => $decodedFirstJson[1][2],
));

echo json_encode($createFinalJsonArr);