PHP:生成json的替代方法?

时间:2015-06-01 23:13:23

标签: php json

我正在努力和新的如何在PHP中的数组上生成json。是否有任何替代方法或最佳方式在PHP上生成json?

HERE'我的代码:

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

这是我如何使用我想要的格式生成json。它有效但有没有人可以为我提供另一种生成这种json格式的方法?

输出:

{"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 个答案:

答案 0 :(得分:2)

你可以让一个类在对象上运行json_encode()。

<?php
class Person {
    public $name;
    public $age;
}
$person = new Person();
$person->name = 'Foo';
$person->age = 22;

echo json_encode($person);

这是最简单的形式,所以如果你没有读过我建议你做的课程和对象。

http://php.net/manual/en/language.oop5.php

答案 1 :(得分:1)

我发现了这种方式,但它并没有让我达到我想要的格式。

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

答案 2 :(得分:0)

由于常见的本机PHP json错误,许多人之前使用过Zend_Json。但是没有任何区别。

我个人最喜欢的是JMS / Serializer,它使用元数据映射或使用注释来序列化数组和对象。只要您有一些Entity / DAO表示,您就可以简单地定义(un)serilalizing模式,只需序列化对象或对象集合,而无需定义自定义数组。

文档:http://jmsyst.com/libs/serializer

Github:https://github.com/schmittjoh/serializer