我的简单循环采用坐标和地名的列表,例如:
(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
)
)
当我尝试直接在循环中修改元素时,是否存在我做错或者不知道的事情?
答案 0 :(得分:0)
在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
用于此目的。但是没有人在第一天成为大师......