0

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"}];

Aaru
  • 803
  • 4
  • 13
  • 29
  • Possible duplicate: http://stackoverflow.com/questions/2122233/convert-php-result-array-to-json – Rahul Desai Jan 09 '14 at 06: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 Jan 09 '14 at 06:02
  • The problem is that you don't want property names quoted and integers as strings? – JAL Jan 09 '14 at 06:08

4 Answers4

1

You dont need to use array_splice(). Just use:

json_encode($myArray);
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
0

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);
zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

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.

Dennis C
  • 24,511
  • 12
  • 71
  • 99
0

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);
Zainul Abdin
  • 835
  • 4
  • 10