如何使用PHP在一行中完成此操作


How to do this in one line using PHP

我有以下结构:

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

其中par1, par2和par3是字符串。如何将par4和par5链接到一行

这不起作用,因为我猜数组/对象嵌套:

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

错误如下:

Undefined property: stdClass::$o

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

如果您总是需要数组的第一个(第0个)值,则此操作有效。

还可以创建返回第n个值的函数:

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

我不确定你真正需要的是什么,但尝试使用{}来突出显示你需要的

{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]}