TDave00
TDave00

Reputation: 374

Defining elements in an array dynamically

I apologize for the title beforehand, but wasn't even sure how to ask the question.

I am working with a json array from a youtube feed. The feed for a playlist and a user upload are formatted a little differently. In order to reduce the amount of code I want to define the elements based on the type of feed (playlist/user upload) and insert that into my foreach statement.

The foreach statement for user uploads looks like this:

foreach ($json_output->data->items as $data)    {}

and for the playlist it needs to look like this:

foreach ($json_output->data->items->video as $data)   {}

I have tried defining the statement in a variable beforehand and doing something as follows with no luck:

foreach ($json_output.$feedtype as $data)   {}

or

foreach ($json_output + $feedtype as $data)   {}

Upvotes: 0

Views: 46

Answers (2)

TDave00
TDave00

Reputation: 374

$feed was already defined, so here is what I did.

foreach ( $json_output->data->items as $feed_data ){
if ($feed == 1) {$data = $feed_data;}
else {$data = $feed_data->video;}

Upvotes: 0

bitWorking
bitWorking

Reputation: 12665

The easiest thing I could think of is to make an if condition on the feedtype:

$feedtype = 'uploads'; // or playlist

if ($feedtype == 'uploads') {
    $array = $json_output->data->items;
}
else if ($feedtype == 'playlist') {
    $array = $json_output->data->items->video;
}

foreach ($array as $data) {}

Upvotes: 1

Related Questions