gpt4 book ai didi

php - foreach中直接修改数组元素导致value覆盖下一个元素

转载 作者:搜寻专家 更新时间:2023-10-31 21:57:56 25 4
gpt4 key购买 nike

我的简单循环采用坐标和地名列表,例如:

(59.436961) (24.753575) (Revel, Estonia) (Born)
(-34.847745) (138.507362) (Port Adelaide) (Disembarked)
(-33.177085) (138.010057) (Port Pirie) (Residence before enlistment)

preg_split将它们放入数组 $coords 中,效果很好。然后我在 foreach 循环中遍历它们。我的问题是为什么这样做:

foreach ($coords as &$marker){
$marker = preg_split('/\\) \\(|\\(|\\)/', $marker, -1, PREG_SPLIT_NO_EMPTY);
}
print_r($coords);

结果:

Array
(
[0] => Array
(
[0] => 59.436961
[1] => 24.753575
[2] => Revel, Estonia
[3] => Born
)

[1] => Array
(
[0] => -34.847745
[1] => 138.507362
[2] => Port Adelaide
[3] => Disembarked
)

[2] => Array
(
[0] => -34.847745
[1] => 138.507362
[2] => Port Adelaide
[3] => Disembarked
)

)

(请注意,元素 [1] 和 [2] 是相同的)- 但是:

foreach ($coords as $marker){
$marker_array[] = preg_split('/\\) \\(|\\(|\\)/', $marker, -1, PREG_SPLIT_NO_EMPTY);
}
print_r($marker_array);

结果:

Array
(
[0] => Array
(
[0] => 59.436961
[1] => 24.753575
[2] => Revel, Estonia
[3] => Born
)

[1] => Array
(
[0] => -34.847745
[1] => 138.507362
[2] => Port Adelaide
[3] => Disembarked
)

[2] => Array
(
[0] => -33.177085
[1] => 138.010057
[2] => Port Pirie
[3] => Residence before enlistment
)

)

当我尝试直接在循环中修改元素时,是否有我做错或不知道的地方?

最佳答案

在 PHP 5.6 中,我没有看到所描述的行为。你如何解析原始列表?

当我运行时:

<?php

$coords = array('(59.436961) (24.753575) (Revel, Estonia) (Born)',
'(-34.847745) (138.507362) (Port Adelaide) (Disembarked)',
'(-33.177085) (138.010057) (Port Pirie) (Residence before enlistment)');

foreach ($coords as &$marker){
$marker = preg_split('/\\) \\(|\\(|\\)/', $marker, -1, PREG_SPLIT_NO_EMPTY);
}
print_r($d);

它给了我这个:

Array
(
[0] => Array
(
[0] => 59.436961
[1] => 24.753575
[2] => Revel, Estonia
[3] => Born
)

[1] => Array
(
[0] => -34.847745
[1] => 138.507362
[2] => Port Adelaide
[3] => Disembarked
)

[2] => Array
(
[0] => -33.177085
[1] => 138.010057
[2] => Port Pirie
[3] => Residence before enlistment
)

)

但我不推荐使用这种疯狂的结构!

如果你从文本中解析它,那么只需使用 preg_match_all 和类似这样的模式:

'~\(()\)\s*\(()\)\s*\(()\)\s*\(()\)~mu'

即使您有数组中的数据,我也强烈建议您使用 preg_match 进行可预测的数据匹配,而不是为此目的使用 preg_split。但是没有人在第一天就成为大师......

关于php - foreach中直接修改数组元素导致value覆盖下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31579166/

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