[英]PHP: Elegant Way to foreach Over a Subarray of an Associative Array
I have an associative array of arrays. 我有一个关联的数组数组。 The associative array of arrays does not always contain the same sub-arrays.
关联数组数组并不总是包含相同的子数组。 I would like to loop through a particular sub-array if it exists.
如果它存在,我想循环一个特定的子数组。 Is there a more elegant way to do the following code:
是否有更优雅的方式来执行以下代码:
if ( array_key_exists( 'fizzy_drinks', $drinks ) ) {
foreach ( $drinks['fizzy_drinks'] as $fizzy_drink ) {
// do something with $fizzy_drink
}
}
Not really, this is as much elegant as it gets: 不是真的,这是优雅的:
if (isset($drinks['fizzy_drinks'])) {
foreach ( $drinks['fizzy_drinks'] as $fizzy_drink ) {
// do something with $fizzy_drink
}
}
If you omit the isset you will get a notice if fizzy_drinks is not set, and a warning if $drinks is not an array. 如果省略isset,如果未设置fizzy_drinks,则会收到通知,如果$ drinks不是数组,则会收到警告。
You can use: 您可以使用:
if (! empty($drinks['fizzy_drinks']) && is_array($drinks['fizzy_drinks'])) {
foreach ($drinks['fizzy_drinks'] as $fizzy_drink) {
// do something with $fizzy_drink
}
}
no warnings, no notices 没有警告,没有通知
Not really. 并不是的。 I think your solution is quite elegant, and readable.
我认为您的解决方案非常优雅,可读。 I would do:
我会做:
if (array_key_exists('fizzy_drinks', $drinks) && is_array($drinks['fizzy_drinks'])) {
foreach ($drinks['fizzy_drinks'] as $fizzy_drink ) {
// do something with $fizzy_drink
}
}
Always nice to check if the value you try to use foreach
on really is an array. 总是很高兴检查你尝试使用
foreach
的值是否真的是一个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.