How to do this in one line using PHP

I have the following structure:

$par4 = json_decode($source_code)->$par1->$par2->$par3;
$par5 = $par4[0]->attributes->attribute[1]->value;

where par1, par2 and par3 are strings. How do I chain the par4 and par5 on one line.

This does not work because of the array / object nesting I guess:

json_decode($source_code)->$par1->$par2->$par3[0]->attributes->attribute[1]->value;

Here's the error:

Undefined property: stdClass::$o

Upvotes: 0

Views: 100

Answers (2)

Calonthar
Calonthar

Reputation: 168

What about

$par5 = current(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;

This works if you are always need in the first (0th) value of the array.

You can also create a function that returns the nth-value:

function third_value($arr) { return $arr[2]; }
$par5 = third_value(json_decode($source_code)->$par1->$par2->$par3)->attributes->attribute[1]->value;

Upvotes: 3

RiaD
RiaD

Reputation: 47619

I'm not sure, what you really need but try using {} to highlight what you need

{json_decode($source_code)->$par1->$par2->$par3}[0] // I think this is right
json_decode($source_code)->$par1->$par2->${par3[0]}
json_decode($source_code)->$par1->$par2->{$par3[0]}

Upvotes: 1

Related Questions