php 从数组中删除键 => 值对,但不删除它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7035332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing key => value pairs from an array, but its not removing them
提问by Drewdin
I am trying to remove two key value pairs from an array, I am using the code below to segregate out the keys I don't want. I don't understand why it is not equating properly. if I remove the OR (|| $key != 6
) it will work properly but I was hoping to have one if statement. Can anyone explain what I'm doing wrong? Thanks.
我正在尝试从数组中删除两个键值对,我正在使用下面的代码来隔离我不想要的键。我不明白为什么它不正确地等同。如果我删除 OR ( || $key != 6
) 它将正常工作,但我希望有一个 if 语句。谁能解释我做错了什么?谢谢。
$test = array( '1' => '21', '2' => '22', '3' => '23', '4' => '24', '5' => '25', '6' => '26' );
foreach( $test as $key => $value ) {
if( $key != 4 || $key != 6 ) {
$values[$key] = $value;
echo '<br />';
print_r( $values );
}
}
// Output
Array ( [1] => 21 [2] => 22 [3] => 23 [4] => 24 [5] => 25 [6] => 26 )
回答by Jonah
This is the best way to do that:
这是最好的方法:
$values = $test;
unset($values[4], $values[6]);
Assuming that you need a new array $values
. Otherwise remove them directly from $tests
.
假设您需要一个新数组$values
。否则直接从$tests
.
Reference here: http://php.net/unset
参考这里:http: //php.net/unset
The following is just for your own education in boolean logic, it's not the way you should do it.
以下仅用于您自己的布尔逻辑教育,这不是您应该做的。
You need to change ||
to &&
. You don't want eitherin the result. With logical OR, all of them will get through because 4 != 6
and 6 != 4
. If it hits 4
, it will run like this:
您需要更改||
为&&
. 你不想要任何结果。使用逻辑 OR,它们都将通过,因为4 != 6
和6 != 4
。如果命中4
,它会像这样运行:
Are you not equal to 4? Oh, you areequal to 4? Well, the best I can do is let you though if you're not equal to 6.
你不等于4吗?哦,你是等于4?好吧,如果你不等于6,我能做的最好的就是让你。
If you change it to &&
, it will run something like this:
如果将其更改为&&
,它将运行如下所示:
Are you a number besides 4 or 6? No? Sorry pal.
你是除了 4 还是 6 之外的数字?不?对不起朋友。
回答by Ignacio Vazquez-Abrams
回答by deceze
Assuming you don't really need the loop, this will do the same thing:
假设你真的不需要循环,这将做同样的事情:
unset($test[4], $test[6])
回答by Rukmi Patel
Your condition is wrong. if you dont want to take key 4 and 6 then your condition should be like this
你的条件不对。如果你不想拿钥匙 4 和 6 那么你的情况应该是这样的
foreach( $test as $key => $value ) {
if( $key != 4 && $key != 6 ) {
回答by Fox
There is a native PHP function:
有一个原生的 PHP 函数:
$values = array_diff_key ($test , array('4'=>'','6'=>''));