Как с помощью цикла выводить нужную инфу с многомерного массива?

154
15 декабря 2018, 09:50

Вот сам массив, результат:

stdClass Object
(
[kind] => youtube#searchListResponse
[etag] => "XI7nbFXulYBIpL0ayR_gDh3eu1k/ryruWPr4aQ4rbpENp_4OB3QeBBU"
[nextPageToken] => CAMQAA
[regionCode] => RU
[pageInfo] => stdClass Object
    (
        [totalResults] => 161302
        [resultsPerPage] => 3
    )
[items] => Array
    (
        [0] => stdClass Object
            (
                [kind] => youtube#searchResult
                [etag] => "XI7nbFXulYBIpL0ayR_gDh3eu1k/NB3gDmojBt_PmLOzy7jCnUmMPoQ"
                [id] => stdClass Object
                    (
                        [kind] => youtube#video
                        [videoId] => kM6JtbnsXDc
                    )
                [snippet] => stdClass Object
                    (
                        [publishedAt] => 2017-07-14T16:32:54.000Z
                        [channelId] => UCZnxD9WE_p6YgrjK6EKNvOg
                        [title] => ТРЕШ ОБЗОР ФИЛЬМА Обитель Зла Вендетта. Мультики!
                        [description] => ТаймВидеоГейм (TVG) -  Смешной обзор фильма Обитель Зла Вендетта, где всеми любимые Леон Кеннеди...
                        [thumbnails] => stdClass Object
                            (
                                [default] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/kM6JtbnsXDc/default.jpg
                                        [width] => 120
                                        [height] => 90
                                    )
                                [medium] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/kM6JtbnsXDc/mqdefault.jpg
                                        [width] => 320
                                        [height] => 180
                                    )
                                [high] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/kM6JtbnsXDc/hqdefault.jpg
                                        [width] => 480
                                        [height] => 360
                                    )
                            )
                        [channelTitle] => TerlKabot channel
                        [liveBroadcastContent] => none
                    )
            )
        [1] => stdClass Object
            (
                [kind] => youtube#searchResult
                [etag] => "XI7nbFXulYBIpL0ayR_gDh3eu1k/i8H21ubJAL5sqTYMT_-sSrMG6Xw"
                [id] => stdClass Object
                    (
                        [kind] => youtube#video
                        [videoId] => gGAImym_LfY
                    )
                [snippet] => stdClass Object
                    (
                        [publishedAt] => 2017-06-12T20:56:38.000Z
                        [channelId] => UCz97F7dMxBNOfGYu3rx8aCw
                        [title] => Resident Evil: Vendetta - Watch the First 9 Minutes- In Theaters One Night Only 6/19
                        [description] => A death merchant is spreading a deadly virus in New York to avenge his wife's death. Chris Redfield enlists the help of Leon Kennedy and Rebecca Chambers ...
                        [thumbnails] => stdClass Object
                            (
                                [default] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/gGAImym_LfY/default.jpg
                                        [width] => 120
                                        [height] => 90
                                    )
                                [medium] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/gGAImym_LfY/mqdefault.jpg
                                        [width] => 320
                                        [height] => 180
                                    )
                                [high] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/gGAImym_LfY/hqdefault.jpg
                                        [width] => 480
                                        [height] => 360
                                    )
                            )
                        [channelTitle] => Sony Pictures Entertainment
                        [liveBroadcastContent] => none
                    )
            )
        [2] => stdClass Object
            (
                [kind] => youtube#searchResult
                [etag] => "XI7nbFXulYBIpL0ayR_gDh3eu1k/GqR4xiWGVu8ZiNIOGE2rovsHr3I"
                [id] => stdClass Object
                    (
                        [kind] => youtube#video
                        [videoId] => Fs5g-l0Bcss
                    )
                [snippet] => stdClass Object
                    (
                        [publishedAt] => 2016-12-22T16:14:59.000Z
                        [channelId] => UCuuU2L90sqhQahV1IkhCPaQ
                        [title] => Resident Evil: Vendetta Official Trailer #1 (2017) Animated Movie HD
                        [description] => Resident Evil: Vendetta Trailer 1 (2017) Animated Movie HD [Official Trailer]
                        [thumbnails] => stdClass Object
                            (
                                [default] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/Fs5g-l0Bcss/default.jpg
                                        [width] => 120
                                        [height] => 90
                                    )
                                [medium] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/Fs5g-l0Bcss/mqdefault.jpg
                                        [width] => 320
                                        [height] => 180
                                    )
                                [high] => stdClass Object
                                    (
                                        [url] => https://i.ytimg.com/vi/Fs5g-l0Bcss/hqdefault.jpg
                                        [width] => 480
                                        [height] => 360
                                    )
                            )
                        [channelTitle] => Zero Media
                        [liveBroadcastContent] => none
                    )
            )
    )
)

PHP:

$res = json_decode($res_json);
print_r($res);

Как мне построить c помощью foreach на подобии вод такого : HTML:

$res[title]<br>
<iframe width="560" height="315" 
src="https://www.youtube.com/embed/'.$res[videoId].'" frameborder="0" 
allowfullscreen></iframe><br>

?

Answer 1

Во первых у Вас не массив, а объект.

При желании json_decode принимает параметр, который преобразует результат не в объект stdClass, а в ассоциативный массив.(http://php.net/manual/ru/function.json-decode.php)

Цикл будет выглядеть примерно так:

foreach($res->items as $resItem){
     $resItem->snippet->title<br>
     <iframe width="560" height="315" 
      src="https://www.youtube.com/embed/'.$resItem->id->videoId.'" frameborder="0" 
     allowfullscreen></iframe><br>
}
Answer 2

Вот что мне нужно было, пользуйтесь))

 foreach($res->items as $item) {
 print $item->snippet->title.'<br>';
 print '
 <iframe width="560" height="315" src="https://www.youtube.com/embed/'.$item- 
 >id->videoId.'" frameborder="0" allowfullscreen></iframe><br>
 ';
 }
READ ALSO
Не работает условие в цикле foreach

Не работает условие в цикле foreach

Данные он записываетНо если добавить в условие:

107
Полное скачивание страницы php

Полное скачивание страницы php

Есть следующий код, предназначенный для показа страницы, адрес которой указан в переменной $url:

131
Как в Laravel использовать belongsTo hasMany в модели?

Как в Laravel использовать belongsTo hasMany в модели?

Знаю как работают relation-и в контроллере но как использовать их в моделях где они объявлены ?

125