gpt4 book ai didi

php - 出现未知数组元素?

转载 作者:行者123 更新时间:2023-12-02 22:14:44 25 4
gpt4 key购买 nike

我正在写一段代码,突然发现,出现了一些奇怪的值。

    function purify($output){
$temp = 0;
$max_index = count($output);
for($i=0;$i < $max_index; $i++){
if(strlen($output[$i]) == 3){
$str = str_split($output[$i]);
arsort($str);
$str = implode($str);
$output[$temp] = $str;
$temp++;
}
else unset($output[$i]);
}
return array_unique($output);
}

当我传递一个由这些元素组成的数组时:

11 115 165 138 999 885 999 456 135 726 642 425 426

我得到这个输出:

array(11) { [1]=> string(3) "651" [2]=> string(3) "831" [3]=> string(3) "999" [4]=> string(3) "885" [6]=> string(3) "654" [7]=> string(3) "531" [8]=> string(3) "762" [9]=> string(3) "642" [10]=> string(3) "542" [12]=> string(3) "426" [0]=> string(3) "511" }

$temp 只上升到 11 时,第 12 个元素 ([12]=> string(3) "426") 是如何到达那里的?我无法理解它。

最佳答案

在遍历数组时更改数组 $output 不是一个好习惯。

考虑创建一个名为 $result 的新数组并更改此行:

 $output[$temp] = $str;

到:

 $result[$temp] = $str;

这样在循环结束前你不会触及$output

在我看来,您看到的索引很奇怪,因为您对 $output 的更改会影响下一次迭代。

关于php - 出现未知数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675203/

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