Php 正在删除数组中的0值
我尝试了这两种方法来从该数组中删除0值,但均无效Php 正在删除数组中的0值,php,arrays,Php,Arrays,我尝试了这两种方法来从该数组中删除0值,但均无效 foreach ($matches as $array_key=>$array_item) { if($matches[$array_key] == 0) { unset($matches[$array_key]); } } var_dump ($matches[$array_key]); 还有这个 $matches_without_nulls = array_filter($matches); print_r($m
foreach ($matches as $array_key=>$array_item)
{
if($matches[$array_key] == 0)
{
unset($matches[$array_key]);
}
}
var_dump ($matches[$array_key]);
还有这个
$matches_without_nulls = array_filter($matches);
print_r($matches_without_nulls[1]);
然而,我一直得到的线索是
{ [0] => string(7) "2337667" [1] => string(7) "2335765" [2] => string(7) "2332651" [3] => string(7) "2328582" [4] => string(1) "0" [5] => string(1) "0" [6] => string(1) "0" [7] => string(1) "0" }
知道发生了什么吗?尝试改变:
if($matches[$array_key] == 0)
到
您的数组不包含0个整数,它包含0个字符串: 那就行了 PS:为什么要打印一个不存在的值$matches[$array\u key]?它已取消设置,因此提供NULL。使用var_dump$matches;测试代码 我刚试过这个,效果很好:
$matches = array (
"2337667",
"2335765",
"2332651",
"2328582",
"0",
"0",
"0",
"0"
);
foreach ( $matches as $array_key => $array_item ) {
if( $matches[$array_key] == "0") {
unset($matches[$array_key]);
}
}
var_dump ($matches);
//output
array(4) {
[0]=> string(7) "2337667"
[1]=> string(7) "2335765"
[2]=> string(7) "2332651"
[3]=> string(7) "2328582"
}
您可以使用数组过滤器函数。单击下面的url
您的原始代码实际上是。你最好使用这个函数
array_filter($matches, function($e){return $e!=0;});
仅阵列过滤器。我不知道为什么它对您不起作用。比较值,而不是使用键
foreach($matches as $array_key=>$array_item)
{
if( $array_item == 0 ) // if($matches[$array_key] == 0)
{
unset($matches[$array_key]);
}
}
var_dump ($matches);
或
你也可以试试下面的方法
foreach($matches as $array_key=>$array_item)
{
if( !$array_item ) // if $array_item is below, it will get in the loop and excute your code.
{
unset($matches[$array_key]);
}
}
var_dump ($matches);
嗨,伙计们,我相信Dainis Abols,因为他帮我解决了这个问题 问题是多指标;这是可行的解决方案
foreach($matches[1] as $array_key=>$array_item)
{
if($matches[1][$array_key] == "0")
{
unset($matches[1][$array_key]);
}
}
var_dump ($matches[1])
) 我不认为这是问题所在。您可以在不回调的情况下使用array_filter,所有等于FALSE的输入项都将被删除。其中0等于0是的,我知道这一点。但是see OP在没有参数的情况下进行了尝试,但没有成功;为什么[1]。在我看来,您没有正确访问数据。
foreach($matches as $array_key=>$array_item)
{
if( !$array_item ) // if $array_item is below, it will get in the loop and excute your code.
{
unset($matches[$array_key]);
}
}
var_dump ($matches);
foreach($matches[1] as $array_key=>$array_item)
{
if($matches[1][$array_key] == "0")
{
unset($matches[1][$array_key]);
}
}
var_dump ($matches[1])