Php 删除foreach循环中的数组元素
我有一个简单的数组,其中包含所有国家的名称和每个国家在我的网站上注册的用户总数。是这样的:Php 删除foreach循环中的数组元素,php,Php,我有一个简单的数组,其中包含所有国家的名称和每个国家在我的网站上注册的用户总数。是这样的: Array ( [1] => Array ( [name] => Afghanistan [total] => 3 ) [2] => Array ( [name] => Albania [total] => 0 ) ) 并且,我正在尝试删除具有0个用户的数组元素(国家) 我已尝试使用此代码,但它不起作用: foreach($country as $ro
Array (
[1] => Array ( [name] => Afghanistan [total] => 3 )
[2] => Array ( [name] => Albania [total] => 0 )
)
并且,我正在尝试删除具有0个用户的数组元素(国家)
我已尝试使用此代码,但它不起作用:
foreach($country as $row) {
if ($row['total'] == 0) {
unset($row);
}
}
此代码有什么问题?如果取消设置($row)
则仅删除局部变量
取而代之的是获取密钥并删除:
foreach ($country as $i => $row) {
if ($row['total'] == 0) {
unset($country[$i]);
}
}
Foreach在循环的数组上创建键/值的副本,因此您所做的只是取消设置本地副本,而不是数组中的原始副本。或者直接访问阵列
foreach($country as $key => $row) {
if ($row['total'] == 0) {
unset($country[$key]);
}
}
或者使用引用,将其取消设置,然后过滤空元素:
foreach($country as &$row) {
if ($row['total'] == 0) {
$row = (unset) $row;
}
}
unset($row);
$country = array_filter($country);
因为$row是值,而不是整个元素 尝试: foreach($country as$key=>$value){ 如果($row['total']==0){ 未设置($country[$key]); }
}顺便说一句,引用不起作用。它仍然只是一个局部变量。;)此外,最好将
unset($val)
放在foreach
循环之后,以删除引用(这也可以省去答案的最后一段)。如果在$row
之前添加一个&
符号(按引用传递),可能会出现重复的情况?