[英]What is the most elegant way to do “foreach x except y” in PHP?
I want to do something like this: 我想做这样的事情:
foreach ($array as $key=>$value except when $key="id")
{
// whatever
}
... without having to put an "if" clause inside the body of the loop. ...无需在循环体内放置“if”子句。 It is not guaranteed that "id" will the be the first or last element in the array, and I don't really want to unset or slice the array, because that will be expensive, ugly, and not maintain the original data. 不能保证“id”将成为数组中的第一个或最后一个元素,并且我真的不想取消设置或切片数组,因为这将是昂贵,丑陋,并且不能维护原始数据。 I also definitely need to use both key and value inside the loop. 我也肯定需要在循环中使用键和值。
Any ideas? 有任何想法吗?
I don't think that the if-clause is such a problem: 我认为if子句不是这样的问题:
foreach ($array as $key => $value) {
if ($key == 'ignore_me') continue;
if ($key == 'ignore_me_2') continue;
If you want a fancy solution, you can use array_diff_key
: 如果你想要一个奇特的解决方案,你可以使用array_diff_key
:
$loop_array = array_diff_key($actual_array, array('ignore_me' => NULL, 'ignore_me_2' => NULL));
foreach ($loop_array as $key => $value) {
#...
Go with the if-clause inside the loop. 在循环中使用if子句。 There is nothing inelegant about it, it is the easiest to read and understand, and it is the most efficient. 它没有任何优雅,它是最容易阅读和理解的,它是最有效的。
If you have many keys to skip you could build a second hash to test against (in the if-clause): 如果你有许多要跳过的键,你可以构建第二个哈希来测试(在if子句中):
foreach ($array as $key => $value) {
if (array_key_exists($key,$skip_keys)) continue;
...
}
I think you'll always end up to use an IF clause in the inner loop. 我想你总是会在内循环中使用IF子句。 Of all the options you already gave, that's the only one I would use for the speed and the memory consumption 在您已经提供的所有选项中,这是我用于速度和内存消耗的唯一选项
Another way of compacting the if
statement is: 压缩if
语句的另一种方法是:
// ignore 1,5,8,9
foreach($arr as $key){
if(in_array($key, array(1,5,8,9)) continue;
...
}
AFAIK you can't do it without an if
in the loop. if
没有循环中的if
,你就无法做到AFAIK。
Like the keyword says, it's "for each", not "for most". 就像关键字所说的那样,它是“为每个人”,而不是“对于大多数人”。
EDIT: like soulmerge says, you could do it with array_diff_key()
, but if you're only missing out a single key it's more verbose and less memory efficient than just putting the if
in the loop. 编辑:像soulmerge说的那样,你可以用array_diff_key()
做到这一点,但是如果你只错过了一个单独的密钥,它就比把if
放在循环中更加冗长,内存效率更低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.