我想将对象转换为JSON,并可以选择要转换的属性。
<?php
class MyObject
{
protected $id;
protected $name;
protected $sub1;
protected $sub2;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
$this->sub1 = new MySubObject;
$this->sub2 = new MySubObject;
}
public function json(array $array)
{
$arrayJson = array();
foreach ($array as $value) {
$arrayJson[$value] = $this->////////// HERE /////// ;
}
return json_encode($arrayJson);
}
public function debug()
{
echo '<pre>';
var_dump($this);
echo '</pre>';
}
}
然后调用这样的东西:
$MyObject= new MyObject(1, 'waffles');
$MyObject->debug();
echo $MyObject->json(array('id','name','sub1->x','sub2->z'));
调试输出:
object(Produto)#3 (3) {
["id":protected]=>
string(1) "1"
["name":protected]=>
string(6) "waffles"
["sub1":protected]=>
object(MySubObject)#3 (3) {
["x"]=>
1
["y"]=>
2
["z"]=>
3
}
["sub2":protected]=>
object(MySubObject)#3 (3) {
["x"]=>
1
["y"]=>
2
["z"]=>
3
}
}
我希望 JSON 的输出如下所示:
{ "id": 1, "name": "waffles", "sub1": {"x": 1}, "sub2": {"z": 3} }
我在制定"json"函数时遇到问题,也许这不是最好的方法。或者,您可以通过选择要转换的字段来判断是否有其他方法可以将对象转换为 JSON。
我忘了说对象可以在子对象中具有子对象。
您可能需要做这样的事情。请注意,这应该可以让您入门,您可以完成它以获得您想要的确切输出:
public function json(array $array)
{
$arrayJson = array();
foreach ($array as $key => $value) {
# See if there is a relation
if(strpos($value,'->') !== false) {
# Explode and remove any empty fields
$subobjexp = array_filter(explode('->',$value));
# See if there is an internal param with this value
if(isset($this->{$subobjexp[0]})) {
# Assign a shorthand variable
$arg = $this->{$subobjexp[0]};
# If there is a second arg, try and extract
if(isset($subobjexp[1]))
$arrayJson[$subobjexp[0]][$subobjexp[1]] = (!empty($arg->{$subobjexp[1]}))? $arg->{$subobjexp[1]} : false;
}
}
else
$arrayJson[$key] = $value;
}
return json_encode($arrayJson);
}
请注意,像 x
和 z
这样的参数必须是 MySubObject
类中的公共变量,否则如果没有其他子类中的 get-type 方法,您将无法访问它们。
> Rasclatt的回答帮助我设置了这个函数。
public function json(array $array)
{
$arrayJson = array();
foreach ($array as $key => $value) {
if (strpos($value, '->') !== false) {
$subobjexp = explode('->', $value);
$arr = array();
$ref = &$arr;
while ($key = array_shift($subobjexp)) {
$ref = &$ref[$key];
}
$subobjexp = explode('->', $value);
eval("$ref = $this->$value;");
$arrayJson[$subobjexp[0]] = $arr[$subobjexp[0]];
} else {
eval("$arrayJson[$value] = $this->$value;");
}
}
return json_encode($arrayJson);
}
当然,它仍然需要一些润色,我没有使用足够的时间来显示错误。如果有人想指出错误或改进,谢谢。