我有一个多维数组,我想循环并打印存储在数组中的值。这是我期待实现的最终结果
{ "lat": 52.4469601, "lon": -1.93685532},
{ "lat": 52.44332417, "lon": -1.9426918},
{ "lat": 52.43987106, "lon": -1.9329071}
我如何打印这样的值?目前这就是我打印整个阵列的方式:
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$decoded = base64_decode($enc);
$trim = trim($decoded, '|');
$data = explode('|', $decoded);
$out = array();
$step = 0;
$last = count($data);
$last--;
foreach( $data as $key => $item ) {
foreach (explode(',', $item) as $value) {
$out[$key][] = $value;
}
}
echo "<pre>";
print_r( $out );
echo "</pre>";
输出如下:
Array
(
[0] => Array
(
[0] => 52.4469601
[1] => -1.93685532
)
[1] => Array
(
[0] => 52.44332417
[1] => -1.9426918
)
[2] => Array
(
[0] => 52.43987106
[1] => -1.9329071
)
[3] => Array
(
[0] => 52.4454953
[1] => -1.92582607
)
)
答案 0 :(得分:1)
如果您的数据始终使用“lat”和“lon”对导出,则可以执行以下操作:
foreach( $data as $key => $item ) {
$lat = true;
foreach (explode(',', $item) as $value) {
if($lat == true){
$out[$key]["lat"] = $value;
$lat = false;
} else {
$out[$key]["lon"] = $value;
}
}
}
答案 1 :(得分:0)
使用流方法执行此操作的另一种方法:
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$handle = fopen("data:text/plain;base64,$enc", 'r');
$res = [];
while ( false !== $rec = stream_get_line($handle, 0, '|') ) {
$res[] = array_combine(['lat', 'lon'], str_getcsv($rec));
}
echo json_encode($res);
答案 2 :(得分:0)
$enc = 'NTIuNDQ2OTYwMSwtMS45MzY4NTUzMnw1Mi40NDMzMjQxNywtMS45NDI2OTE4fDUyLjQzOTg3MTA2LC0xLjkzMjkwNzF8NTIuNDQ1NDk1MywtMS45MjU4MjYwN3w';
$decodedArr = explode('|', base64_decode($enc));
$latLong = [];
foreach ($decodedArr as $latLongStr) {
if (!$latLongStr) {
continue;
}
$temp = explode(',', $latLongStr);
$latLong[] = ['lat' => $temp[0], 'lon' => $temp[1]];
}
echo json_encode($latLong);
输出
[{"lat":"52.4469601","lon":"-1.93685532"},{"lat":"52.44332417","lon":"-1.9426918"},{"lat":"52.43987106","lon":"-1.9329071"},{"lat":"52.4454953","lon":"-1.92582607"}]