Reputation: 543
Im working and new how to generate json on arrays in php. is there any alternate ways or best way to generate json on php?
HERE'S MY CODE:
<?php
$array =
array(
'name' =>
array(
'gender'=> 'male-female',
'location' => 'adress here'),
'age' => 'age here',
'about me' => array(array(
'birthday' => 'MM-DD-YYYY',
'status' => 'status here',
'childrens' => 'childrens here')),
'employer' => array('bank','fastfood','sales'),
'nameofchildrens' => array(array(
'name1' => "namehere1" , 'employer2' => array('bank','fastfood','sales'),
'name2' => "namehere2" , 'employer1' => array('bank','fastfood','sales'))),
'relatives' => array(),
'siblings' => array(),
'ancestors' => array(),
'pets' => array(array('dog','cat','rabbit')),
'sports' => array('basketball','badminton','volleyball'),
);
echo json_encode($array);
?>
This how I generate a json with format I wanted. It's working but is there anyone can provide me a alternate ways to generate a json format like this?
OUTPUT:
{"name":{"gender":"male-female","location":"adress here"},"age":"age here","about me":[{"birthday":"MM-DD-YYYY","status":"status here","childrens":"childrens here"}],"employer":["bank","fastfood","sales"],"nameofchildrens":[{"name1":"namehere1","employer2":["bank","fastfood","sales"],"name2":"namehere2","employer1":["bank","fastfood","sales"]}],"relatives":[],"siblings":[],"ancestors":[],"pets":[["dog","cat","rabbit"]],"sports":["basketball","badminton","volleyball"]}
Upvotes: 2
Views: 106
Reputation: 543
I found this way but it doesnt let me to the format I wanted.
<?php
$obj = new stdClass();
$obj->metadata = "Devices per year";
$obj->data = array(
array('1999','3.0'),
array('2000','3.9'),
//and so on...
);
echo json_encode($obj);
?>
Upvotes: 1
Reputation: 833
You could make a class an run json_encode() on the object.
<?php
class Person {
public $name;
public $age;
}
$person = new Person();
$person->name = 'Foo';
$person->age = 22;
echo json_encode($person);
This is in it's simpliest form, so if you havan't read up on classes and objects I suggest you do.
http://php.net/manual/en/language.oop5.php
Upvotes: 2
Reputation: 81
Many people used Zend_Json before because of common native PHP json errors. But there's no difference at all.
My personal favourite is JMS/Serializer which serializes arrays and objects using metadata maps or using annotations. As long as you have some Entity / DAO representation you can simply define (un)serilalizing schema and just serialize objects or object collections without defining custom arrays.
Documentation: http://jmsyst.com/libs/serializer
Github: https://github.com/schmittjoh/serializer
Upvotes: 0