Laravel 如何将模型的属性附加到对象
在Laravel中,我有模型Laravel 如何将模型的属性附加到对象,laravel,object,model,attributes,Laravel,Object,Model,Attributes,在Laravel中,我有模型城市,属性为名称,纬度,长,当我打印城市时,它输出为: { "name": "San Juan", "latitude": 66.66, "longitude": 44.44 } 但是,我需要始终以以下格式打印此文件,并将lat和long放在geolocation对象中 { "name": "San Juan",
城市
,属性为名称
,纬度
,长
,当我打印城市时,它输出为:
{
"name": "San Juan",
"latitude": 66.66,
"longitude": 44.44
}
但是,我需要始终以以下格式打印此文件,并将lat
和long
放在geolocation
对象中
{
"name": "San Juan",
"geolocation": {
"latitude": 66.66,
"longitude": 44.44
}
}
这可以在我的
City.php
model类中完成吗?您将删除lat和long属性,并用新属性替换它们
地理位置及其类型将是json格式{“纬度”:66.66,“经度”:44.44}。试试看
$z= json_decode($y);
$z->geolocation = ['latitude' => $z->latitude,'longitude' => $z->longitude];
unset($z->latitude);
unset($z->longitude);
echo json_encode($z);
输出将是
{
"name":"San Juan",
"geolocation":
{
"latitude":66.66,
"longitude":44.44
}
}
选项是
json\u decode()
将json对象添加到数组并添加必需的字段。然后json\u encode
获取json对象。这是如何得到答案的?