Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:生成json的替代方法?_Php_Json - Fatal编程技术网

PHP:生成json的替代方法?

PHP:生成json的替代方法?,php,json,Php,Json,我正在研究如何在php中的数组上生成json。在php上生成json有其他方法或最佳方法吗 这是我的密码: <?php $array = array( 'name' => array( 'gender'=> 'male-female', 'location' => 'adress here'), 'age' => 'age here',

我正在研究如何在php中的数组上生成json。在php上生成json有其他方法或最佳方法吗

这是我的密码:

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

由于常见的原生PHP Json错误,许多人以前使用Zend_Json。但是没有什么区别

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

文件:


Github:

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

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

echo json_encode($person);

我找到了这种方法,但它不允许我使用我想要的格式

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


嗯,cleaner可能使用
[]
而不是
数组()
。而且是一个刻板的人!除了首先用纯JSON编写之外?不。你可以创建一个Person类,然后在对象上运行json_encode。@Karl你能给我一个例子吗?如果你使用的是PHP5.4+:我以前试过这个,但它不允许我使用我想要的json格式。就像我添加一些array()时一样。在对象上使用
json\u encode()
的问题是,它只会对公共属性进行编码,而私有属性会被跳过。PHP有一个神奇的方法,但对于array/json没有类似的方法。您可以编写一个
toJSON()
方法,根据需要吐回对象的表示并调用它
json\u编码($obj->toJSON())
。一定要从答案中读出来。@ficuscr你能给我举个例子吗
<?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);
?>