I have a PHP array like below:
Array
(
[0] => stdClass Object
(
[id] => 1
[area] => Arappalayam
)
[1] => stdClass Object
(
[id] => 2
[area] => Kalavasal
)
)
Now, I need to convert this array into Json array like below :
$local_source = [
{
id: 1,
area: "Arappalayam"
}, {
id: 2,
area: "Kalavasal"
}
];
I have tried below code to convert json array in php
$availableArea = array_slice($areas[0],0);
return json_encode($availableArea);
But It is not working, any ideas>?
The result came as like [{"id":"1","area":"Arappalayam"},{"id":"2",area:"Kalavasal"}]; but i want [{id:1,area:"Arappalayam"},{id:2,area:"Kalavasal"}];
-
Possible duplicate: stackoverflow.com/questions/2122233/…Rahul Desai– Rahul Desai2014年01月09日 06:00:59 +00:00Commented Jan 9, 2014 at 6:00
-
The result came as like [{"id":"1","area":"Arappalayam"},{"id":"2",area:"Kalavasal"}]; but i want [{id:1,area:"Arappalayam"},{id:2,area:"Kalavasal"}];Aaru– Aaru2014年01月09日 06:02:23 +00:00Commented Jan 9, 2014 at 6:02
-
The problem is that you don't want property names quoted and integers as strings?JAL– JAL2014年01月09日 06:08:14 +00:00Commented Jan 9, 2014 at 6:08
4 Answers 4
You dont need to use array_splice(). Just use:
json_encode($myArray);
Comments
1)
Your "id":"1" but not "id":1 is because your value in PHP are really strings, not int.
Convert them using intval() will have a different result.
2)
No. You cannot generate id: rather then "id":, because keys are quoted string in standard JSON specification. Beside, there are Javascript reserved words could be be key in JSON.
Comments
simply use json_encode
$local_source = json_encode($array);
check docs http://pk1.php.net/json_encode
and when decode it back to php array
$array = json_decode($local_source,true);
Comments
You can follow below given PHP example
$area = array('0' => array('id' => "1",'area' => 'Arappalayam'),
'1' => array('id' => "2",'area' => 'Kalavasal')
);
//callback function to do conversion
function convert($value){
//convert only ID into integer
$value['id'] = intval($value['id']);
return $value;
}
$area = array_map('convert',$area);
echo json_encode($area);