PHP:删除所有不按预期运行的 fcn,代码内部
我做了这个简单的函数(从 $array 中删除所有 $elem):
function remall($array, $elem) {
for($i=0; $i < count($array); $i++)
if($array[$i] == $elem)
unset($array[$i]);
$newarray = array_values($array);
return $newarray;
}
但它运行不完美,这里有一些输入和输出
$u = array(1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7);
$r = remall($u, 7);
Output of $r: 12345767
$n = array(7, 7, 1, 7, 3, 4, 6, 7, 2, 3, 1, -3, 10, 11, 7, 7, 7, 2, 7);
$r = remall($n, 7);
Output of $r: 1346231-30117727
请注意我的输出中仍然有 7。 另外,我的函数只会从数组中删除数字。 如果您发现什么,请告诉我,谢谢。
解决方案:嘿伙计们,这对我有用(感谢 Flavius Stef)
function remall($array, $elem) {
return array_values(array_diff($array, array($elem)));
}
I made this simple function (remove all $elem from $array):
function remall($array, $elem) {
for($i=0; $i < count($array); $i++)
if($array[$i] == $elem)
unset($array[$i]);
$newarray = array_values($array);
return $newarray;
}
But it isn't working perfectly, here are some inputs and outputs
$u = array(1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7);
$r = remall($u, 7);
Output of $r: 12345767
$n = array(7, 7, 1, 7, 3, 4, 6, 7, 2, 3, 1, -3, 10, 11, 7, 7, 7, 2, 7);
$r = remall($n, 7);
Output of $r: 1346231-30117727
Notice how there are still 7s in my outputs.
Also, My function will only be removing numbers from an array.
Let me know if you spot something, thanks.
SOLUTION: Hey guys this is what worked for me (Thanks to Flavius Stef)
function remall($array, $elem) {
return array_values(array_diff($array, array($elem)));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会和
I'd go with
您能否保证输入数组是数字数组(而不是关联数组)并且键中没有“漏洞”?
您可能需要使用
foreach ($array as $key => $value) { ... }
而不是for ($i=0; $i < count($array ); $i++) { ... }
。除了第一段中描述的警告之外,第二种方法(您现在使用的方法)评估
count()
每次迭代for
- 和unset ()
自然会更改该值(首先您的数组有十个元素,然后在第一次匹配后,它将有九个,依此类推)。另一种选择是,完全避免创建自己的函数,您可以使用
array_filter()
并提供自定义回调方法,尽管如果您的标准发生很大变化,这不是一个很好的选择(它是示例中的一个参数,看起来会是; ))。编辑:最好的解决方案(最具可读性和最可维护性,同时完全按照您想要的方式进行)是使用
array_diff()
,按照Flavius Stef 的回答:Can you guarantee the input array is numeric (rather than associative) and without 'holes' in the keys?
You may want to use
foreach ($array as $key => $value) { ... }
rather thanfor ($i=0; $i < count($array); $i++) { ... }
.Aside from the caveat described in the first paragraph, the second approach (the one you're using now) evaluates
count()
each iteration offor
- andunset()
will change that value, naturally (first your array has ten elements, then after the first match, it'll have nine, and so forth).Another option, sidestepping the need to make your own function entirely, would be for you to use
array_filter()
and supply a custom callback method, though that's not a very good option if your criterium changes a lot (which, it being a parameter in your example, it looks like it would be ;) ).Edit: The best solution (most readable and most maintainable, while doing exactly what you want) would be to use
array_diff()
, as per Flavius Stef's answer: