douwang6635 2015-06-01 23:13
浏览 51

PHP:生成json的替代方法?

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"]}
  • 写回答

3条回答 默认 最新

  • doushui3061 2015-06-01 23:26
    关注

    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

    评论

报告相同问题?