Попытка получить свойство addressLine1 не-объекта в Laravel

привет, ребята, я пытался получить доступ к значению через многомерный массив в представлении laravel

мой массив json

{
"results":[
{
"id":4582,
"name":"Rocklands Bouldering Permit",
"description":"This permit guarantees entry to all bouldering areas in Rocklands for the validity duration, including CapeNature, de Pakhuys and Travellers Rest<br><u><strong>All climbers visiting Rocklands must be in possession of this permit to climb on any land and must carry this permit with them at all times </strong></u>.<br><br><strong>Booking Terms and Conditions:</strong><br>The following Terms and Conditions apply to all bookings (walk-in or pre-paid):<br><br>Damage / loss / death<br><br>It is a distinct condition of admission to any protected area, that the Western Cape Nature Conservation Board and the property owners accept no responsibility or liability arising from a visit(s) <br><br>howsoever caused:<ul><li>For any death, injury or illness sustained or suffered by any person.</li><li>For theft/loss/damage to any property, whether allegedly due to the negligence of the board/</li><li>officers/employees/agents or arising from the use of any facilities supplied/made available.</li><li>CapeNature and the landowners accepts NO responsibility for clothing or any items left behind at our facilities.</li><li>From any alleged defect in any utensil/equipment/services/vessel/vehicle.</li><li>From any other conveyance supplied/made available, or from any liquid/food supplied.</li><li>From any other matter arising, in any other manner and from any other cause whatsoever.</li></ul><br><strong>Breaking of the rules</strong><br>CapeNature and the landowners reserves the right to deny access or to evict guests who do not adhere to the rules and regulations of the CapeNature and landowners and/or its reserves. Money paid for these bookings will be forfeited.<br><br><em><strong>These rules include, but are not limited to the following:</strong></em><ul><li>Visitors are to have their bouldering permit with them upon entrance to the reserve.</li><li>No pets allowed on reserves, the only exception will be guide dogs for the blind.</li><li>No collection of bait, removing, damaging or disturbing of fauna or flora</li><li>Rowdy or unwanted behavior</li><li>All tariffs are subject to change without notification.</li><li>Stick to the marked walking trails</li><li>No puff or resin allowed</li><li>Carry out what you carry in</li></ul>",
"url":"https://www.quicket.co.za/events/4582-rocklands-bouldering-permit/",
"imageUrl":"//quicket.azureedge.net/media/0004303_360_360.Png",
"dateCreated":"2014-03-12T16:59:47.467",
"lastModified":"2018-05-31T10:27:35.4102002",
"startDate":"2014-03-13T10:24:00",
"endDate":"2024-03-01T10:24:00",
"venue":{
"id":0,
"name":"Rocklands",
"addressLine1":"",
"addressLine2":"",
"latitude":-32.1786111,
"longitude":18.8911111
},
{
"id":2830,
"name":"ROX TEST EVENT",
"description":"<span style=\"line-height: 20.7999992370605px;\">Description of the event will go here</span><br /><br /><span style=\"line-height: 20.7999992370605px;\">And you can add pictures or even a youtube video or two here! You can also add a <a target=\"_blank\" href=\"http://www.rockingthedaisies.com\">hyperlink</a></span><br /><br /><br /><iframe width=\"640\" height=\"360\" src=\"https://www.youtube.com/embed/soyeZp_3qN4\" frameborder=\"0\" allowfullscreen=\"\"></iframe>",
"url":"https://www.quicket.co.za/events/2830-rox-test-event/",
"imageUrl":"//quicket.azureedge.net/media/0007888_360_360.Jpeg",
"dateCreated":"2013-09-11T13:14:01.283",
"lastModified":"2018-06-05T10:29:28.574536",
"startDate":"2015-05-07T15:17:00",
"endDate":"2024-05-14T00:00:00",
"venue":{
"id":0,
"name":"Roxys cafe ",
"addressLine1":"14 Wandel Street",
"addressLine2":"",
"latitude":-33.931801,
"longitude":18.417017999999985
}
]

я хотел получить значение "имя" внутри массива результатов, которое я могу получить в своем представлении блейда, но когда я пытаюсь получить доступ к "addressLine1" и "addressLine2" из моего блейда, я не могу получить это, и я могу' t для жизни мне понять, что не так с моим кодом.

ниже мой код в лезвии

 @foreach($datas as $data=>$key)
            @for($i=0;$i<2;$i++)
                <h1>{{$datas[$data][$i]['name']}}</h1>
            @endfor
            @if(is_array($key))
                @foreach($key as $k=>$v)
                    @if(is_array($v))
                        @foreach($v as $venue=>$place)
                            {{dd($place['venue']->addressLine1)}}
                        @endforeach
                    @endif
                @endforeach
            @endif
        @endforeach

и это ошибка, которую я получаю, пытаясь получить свойство "addressLine1" не-объекта

Пожалуйста, помогите мне здесь Спасибо заранее

P.S $datas - это мой закодированный json-массив из контроллера


person Praneet Singh Roopra    schedule 19.06.2018    source источник


Ответы (3)


Ваш json имеет синтаксическую ошибку. Если это json, который вы передаете лезвию, это может быть проблемой. Какой код контроллера?

person Sadjad Ghanbarynasab    schedule 19.06.2018
comment
public function getRemoteData(){ $client= new Client([ 'headers'=›['content-type'=›'application/json','Accept'=›'aaplication/json'] ]); $response= $client-›request('GET','URL(здесь не вставляется из соображений безопасности'); $json=$response-›getbody(); $datas=json_decode($json,true); //print_r ($data); //$data=array($datas); return view('index',compact('datas')); //return view('index')-›with('data', json_decode( $data, true)); } это код моего контроллера - person Praneet Singh Roopra; 19.06.2018

Хорошо, ребята, я решил ошибку, но теперь foreach повторяет один и тот же результат 10 раз без всякой причины, как мне это остановить?

вот мой отредактированный код в лезвии

@foreach($datas as $data=>$key)
        @for($i=0;$i<10;$i++)
            <h1>{{$datas[$data][$i]['name']}}</h1>
        @endfor
        @if(is_array($key))
            @foreach($key as $k=>$v)
                @foreach($v as $venue=>$place)
                        <h1>{{$v['venue']['addressLine1']}}</h1>
                        <h1>{{$v['venue']['addressLine2']}}</h1>
                @endforeach
            @endforeach
        @endif
    @endforeach

и вот мой вывод

14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
person Praneet Singh Roopra    schedule 19.06.2018
comment
у вас есть 2 foreach, а последний бесполезен - person JoseSilva; 19.06.2018

Ваш второй foreach бесполезен, попробуйте этот:

@foreach($datas as $data=>$key)
        @for($i=0;$i<10;$i++)
            <h1>{{$datas[$data][$i]['name']}}</h1>
        @endfor
        @if(is_array($key))
            @foreach($key as $v)
                <h1>{{$v['venue']['addressLine1']}}</h1>
                <h1>{{$v['venue']['addressLine2']}}</h1>
            @endforeach
        @endif
@endforeach

Другое улучшение заключается в использовании слова key, когда переменная является ключом массива, а не значением. И for тоже можно заменить. Как это:

@foreach($datas as $data)
        <h1>{{ $data['name'] }}</h1>
        @if(is_array($key))
            @foreach($key as $v)
                <h1>{{ $v['venue']['addressLine1'] }}</h1>
                <h1>{{ $v['venue']['addressLine2'] }}</h1>
            @endforeach
        @endif
@endforeach
person JoseSilva    schedule 19.06.2018