如何在 Laravel 中获取嵌套的键值
Posted
技术标签:
【中文标题】如何在 Laravel 中获取嵌套的键值【英文标题】:How to get nested key values in Laravel 【发布时间】:2021-12-14 21:07:36 【问题描述】:谁能告诉我如何回显或使用嵌套键值。我基本上 get() 这个集合,我正在使用 foreach 做一些进一步的计算。 我的关系结构是 zone.shipping,在这里我想从巢中获取燃料和紧急情况。
["id":614,"weight":"25.000","rate":"150.640","unit":"kg","detail":"normal","zone":"id":5,"zone":"e","company":1,"shipping":"id":1,"company":"fedex","fuel":"19.50","emergency":"1.35","source":1,
"id":1838,"weight":"25.000","rate":"179.610","unit":"kg","detail":"normal","zone":"id":17,"zone":"7","company":2,"shipping":"id":2,"company":"dhl","fuel":"19.75","emergency":"0.50","source":1,
"id":2414,"weight":"25.000","rate":"263.320","unit":"kg","detail":"normal","zone":"id":24,"zone":"6","company":3,"shipping":"id":3,"company":"ups","fuel":"24.00","emergency":"1.30","source":1]
【问题讨论】:
【参考方案1】:将您的数组放入我刚才作为参考的一个变量中
$data = ["id":614,"weight":"25.000","rate":"150.640","unit":"kg","detail":"normal","zone":"id":5,"zone":"e","company":1,"shipping":"id":1,"company":"fedex","fuel":"19.50","emergency":"1.35","source":1,
"id":1838,"weight":"25.000","rate":"179.610","unit":"kg","detail":"normal","zone":"id":17,"zone":"7","company":2,"shipping":"id":2,"company":"dhl","fuel":"19.75","emergency":"0.50","source":1,
"id":2414,"weight":"25.000","rate":"263.320","unit":"kg","detail":"normal","zone":"id":24,"zone":"6","company":3,"shipping":"id":3,"company":"ups","fuel":"24.00","emergency":"1.30","source":1];
获取值
foreach($data as $key => $value)
$fuel[] = $value['zone']['shipping']['fuel'];
$emergency[] = $value['zone']['shipping']['emergency'];
获得燃料和紧急情况的主要方法是
$value['zone']['shipping']['fuel'];
$value['zone']['shipping']['emergency'];
对于具体的索引,你也可以得到:
$data[0]['zone']['shipping']['fuel'];
$data[0]['zone']['shipping']['emergency'];
【讨论】:
这看起来不错。我很快就会试一试。现在我这样做了,它已经奏效了 $fuel = $rate->zone()->first()->shipping()->first()->fuel; $emergency = $rate->zone()->first()->shipping()->first()->emergency;【参考方案2】:您正在寻找data_get()
【讨论】:
以上是关于如何在 Laravel 中获取嵌套的键值的主要内容,如果未能解决你的问题,请参考以下文章
如果在树中嵌套其他值,则获取文本文件(yaml)中的键值[重复]