Reputation: 103
i have an array data and i want to push that data like this :
new LatLng([ 'lat' => -8.3901371, 'lng' => 115.211049 ]),new LatLng([ 'lat' => -8.3901953, 'lng' => 115.2110649 ]),new LatLng([ 'lat' => -8.3902752, 'lng' => 115.2110648 ]),
then i write code like this :
$paths=[];
foreach ($data as $value){
$koord = "new LatLng([
'lat' => $value->wilayah_lat,
'lng' => $value->wilayah_lng
]),";
array_push($paths, $koord);
}
then, i want to access $paths using print_r($paths)
, i always get data like this :
Array ( [0] => new LatLng([ 'lat' => -8.3901371, 'lng' => 115.211049 ]), [1] => new LatLng([ 'lat' => -8.3901953, 'lng' => 115.2110649 ]), [2] => new LatLng([ 'lat' => -8.3902752, 'lng' => 115.2110648 ]),
my question is, how do i access that data array on variable $paths
look like that i want above ?
Upvotes: 2
Views: 88
Reputation: 5166
you can use implode
for this
$paths=[];
foreach ($data as $value){
$koord = "new LatLng([
'lat' => $value->wilayah_lat,
'lng' => $value->wilayah_lng
])"; // remove the , from here .
array_push($paths, $koord);
}
echo implode(',',$paths);
Upvotes: 1
Reputation: 133
To get effect like you want, retrieve data from array like this:
foreach($paths as $path){
echo $path;
}
$paths is the array from which you want to retrieve data.
Upvotes: -1
Reputation: 1414
Array store data with keys. SO your array look like
Array ([0] => 'value ,...)
If you want plain string use this code
implode(',',$array);
Upvotes: 1
Reputation: 41885
Its still in array form, thats why when you print_r
it, it still has its numeric index like the one shown. Either you implode
the final array:
foreach ($data as $value){
$koord = "new LatLng([
'lat' => $value->wilayah_lat,
'lng' => $value->wilayah_lng
])";
$paths[] = $koord;
}
$paths = implode(', ', $paths);
echo $paths;
Or make/initialize $paths
as strings, then continually append/concatenate the rest of the strings in the loop:
$paths = '';
foreach ($data as $value){
$paths .= "new LatLng([
'lat' => $value->wilayah_lat,
'lng' => $value->wilayah_lng
]),";
}
$paths = rtrim($paths, ','); // remove excess/last comma
echo $paths;
Upvotes: 1