gpt4 book ai didi

php - 为什么我不能在 foreach 循环中取消通过引用传递的数组项?

转载 作者:行者123 更新时间:2023-12-04 10:04:56 24 4
gpt4 key购买 nike

我有一个像

[0] Bert14:50
[1] hello
[2] Sarah14:50
[3] bye
[4] Dennis14:50
[5] hi
[6] wow

我想减少它看起来像:
[0] Bert14:50
[1] Sarah14:50
[2] Dennis14:50

我用这段代码实现了这一点:
//Doesn't any number exist in the array item? Then remove item
//by first setting it to NULL, and after the loop do some reindexing etc.
foreach($new_str as $item_key => &$item) {
if (!preg_match('~[0-9]+~', $item)) {
$item = null;
}
}
//Remove null by using unique array...
$new_str = array_values(array_unique($new_str));
//..and then remove first item if it's null
if ($new_str[0] === null) {unset($new_str[0]);}

但是为什么这段代码不删除不包含 0-9 的项目?
为什么我不能像这样取消设置传递的引用值?
foreach($new_str as $item_key => &$item) {
if (!preg_match('~[0-9]+~', $item)) {
//Nothing seems to happen here. Output of $new_str is same as original
//array
unset($item);
}
}

最佳答案

$item在 foreach 中是对值的引用。有关 Unsetting References 的说明,请参阅此页面.

When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed.



正如评论中所指出的,您可以通过像 unset($new_str[$item_key]); 这样的键对数组使用 unset 索引。您不需要引用 &$item .

一个更短的方法是使用 preg_grep匹配一个数字。您不需要量词 +在字符类之后,因为您只检测它是否存在数字。
$new_str = preg_grep("~[0-9]~", $new_str);

或者对示例数据更精确一点,匹配一个数字、冒号和一个数字:
$new_str = preg_grep("~[0-9]:[0-9]~", $new_str);

输出
Array
(
[0] => Bert14:50
[2] => Sarah14:50
[3] => Dennis14:50
)

Php demo

如果要重置 key ,可以使用 array_values($new_str)

关于php - 为什么我不能在 foreach 循环中取消通过引用传递的数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61637082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com