尝试在 PHP Laravel 应用程序中获取非对象的属性

我有以下返回数组的查询


    $wines = Wine::all();


    //Remove type_id and producer_id

    foreach ($wines as $wine) {

        $location = $wine->producer->location;

    }

如果我 echo $wine-> Producer-> location; 这就是我得到的结果;

{"city": "Kavadartsi", "address": "29-ти Ноември, бр. 5, Kavadartsi 1430", "country": "Macedonia"}

所以我需要的唯一属性是我尝试访问的地址

$wine->producer->location->address;

但是当我这样做时,我收到以下错误

Trying to get property 'address' of non-object

如果我将代码更改为

$wine->producer->location['address'];

错误是:

Illegal string offset 'address'


慕的地8271018
浏览 123回答 2
2回答

白板的微信

首先这是错误的:$wine->producer->location->['address'];,你可能想这样做$wine->producer->location['address'];。如果这不起作用,那么查看生产者迁移文件的样子会有很大帮助,但如果我猜它可能是 json 格式的,就像$table->json('location');. 如果是这种情况,那么您可能需要像这样键入强制转换该特定字段:<?phpclass Location extends Model{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The attributes that should be cast.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $casts = [&nbsp; &nbsp; &nbsp; &nbsp; 'location' => 'array',&nbsp; &nbsp; ];}完成此操作后,您现在可以像这样获取数据:$wine->producer->location['address'];

慕标5832272

去掉location后面的箭头:$wine->producer->location['address'];如果您收到相同的错误,并且数据库中的位置采用 JSON 格式,请对其进行 json_decode:$location&nbsp;=&nbsp;json_decode($wine->producer->location,&nbsp;true); $address&nbsp;=&nbsp;$location['address'];
打开App,查看更多内容
随时随地看视频慕课网APP