我对数组有问题。当我将字符串添加到json_encode时,它保存在db中,但是$ object给我[{},{},{}]
你能告诉我我在做什么错吗?
$objects = array();
$objects[] = new Person(1, 'John', 'Smith','java');
$objects[] = new Person(2, 'Stacy', 'Smith','php');
$Db ='./DB.json';
$saveInBase = json_encode($objects);
file_put_contents($Db, $saveInBase);
$loadFromBase = file_get_contents($Db);
$loadFromBase = json_decode($loadFromBase, true);
答案 0 :(得分:0)
请在jsonSerialize
类上实现JsonSerializable,您只需要实现<?php
class Person implements JsonSerializable
{
private $id;
private $name;
private $last_name;
private $lang;
public function __construct($id, $name, $last_name, $lang)
{
$this->id = $id;
$this->name = $name;
$this->last_name = $last_name;
$this->lang = $lang;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$objects = array();
$objects[] = new Person(1, 'John', 'Smith','java');
$objects[] = new Person(2, 'Stacy', 'Smith','php');
$Db ='./DB.json';
$saveInBase = json_encode($objects);
file_put_contents($Db, $saveInBase);
$loadFromBase = file_get_contents($Db);
$loadFromBase = json_decode($loadFromBase, true);
方法,这里有一个示例:
{{1}}