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

3
  • Possible duplicate: stackoverflow.com/questions/2122233/… Commented 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"}]; Commented Jan 9, 2014 at 6:02
  • The problem is that you don't want property names quoted and integers as strings? Commented Jan 9, 2014 at 6:08

4 Answers 4

1

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

json_encode($myArray);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.