I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.
Related
This question already has answers here:
PHP json_decode integers and floats to string
(6 answers)
Closed 3 years ago.
I am trying to add multiple markers into a google map and i have found a way to do that here.
Now I have a json array response from the server as shown below.
// function to get user names and addresses
public function getUserAddresses(Request $request)
{
$users = User::where('address', '!=', null)->select('name', 'address')->get(); //this is a laravel query
$userData = [];
foreach ($users as $user) {
$userData[$user->name] = $user->address;
}
return $userData;
}
This code above is what gives me the response below.
{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}
but for me to use this data it must be in these format as shown below in javascript.
[
["plumber1", -1.2523238641713191,36.87899683074249],
["plumber2", -1.2192245641713191,36.87899687428849],
["allan plumber", -1.2192238641713191,36.87899683068849]
];
You can use this php code
$str = '{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}';
$array =json_decode($str);
$new_array = [];
foreach ($array as $key => $value) {
$coordinates = explode(',',$value);
$coordinate1 = (float) $coordinates[0];
$coordinate2 = (float) $coordinates[1];
$new_array[] = array($key,$coordinate1,$coordinate2);
}
print_r($new_array);
OUTPUT
Array
(
[0] => Array
(
[0] => plumber1
[1] => -1.25232386
[2] => 36.878996830742
)
[1] => Array
(
[0] => plumber2
[1] => -1.2192245641713
[2] => 36.878996874288
)
[2] => Array
(
[0] => allan plumber
[1] => -1.2192238641713
[2] => 36.878996830688
)
)
You can also check the demo here
Here is Javascript version
<script type="text/javascript">
var str = `{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}`;
var obj = JSON.parse(str);
var array = [];
var counter =0;
for (var key in obj) {
var myarr = obj[key].split(",");
array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];
counter++
}
console.log(array);
</script>
Try json_decode
ini_set( 'precision', 17 );
$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);
i need to create chart based on php array and i found something about traversing in stackoverflow posts but those answers doesnt help for converting this:
Array
(
[product sample 1] => Array
(
[0] => Array
(
[hitsTotal] => 63
)
[1] => Array
(
[hitsTotal] => 113
)
)
[product sample 2] => Array
(
[0] => Array
(
[hitsTotal] => 57
)
[1] => Array
(
[hitsTotal] => 107
)
)
)
to
['product sample 1', 63, 113],
['product sample 2', 57, 107]
how to convert?
Assuming $input is the array you present in your post you can do the following:
$output = array();
foreach($input as $key => $value)
{
$obj = array();
$obj[] = $key;
$obj[] = $value[0]['hitsTotal'];
$obj[] = $value[1]['hitsTotal'];
$output[] = $obj;
}
var_dump($output); //This will print it on screen so you can validate the output
To prepare your data for passing to js(client side) as an array of arrays use the following approach (array_walk, array_column, array_merge and json_encode functions):
// supposing that $arr is your initial array
$result = [];
array_walk($arr, function($v, $k) use(&$result){
$hitsTotals = array_column($v, 'hitsTotal');
$result[] = array_merge([$k], $hitsTotals);
});
echo json_encode($result);
The output:
[["product sample 1",63,113],["product sample 2",57,107]]
I have a PHP array that looks like this:
([NAME] => Array ( [0] => 16 [1] => 12 [2] => 4 [3] => 0 ))
([NAME2] => Array ( [0] => 19 [1] => 19 [2] => 0 [3] => 0 ))
([NAME3] => Array ( [0] => 31 [1] => 29 [2] => 2 [3] => 0 ))
This array is generated by PHP by pulling data from a database.
(The array is much larger than this, but for simplicity, I only included 3 records)
I really need this data to be usable in a script that generates a bar graph. For now, I only need the name and the first record. So, for example, in PHP
<?=$array['NAME'][0]?>
<?=$array['NAME2'][0]?>
would echo the information I need from each, but I'm not sure how to put that into the format I need into javascript.
This is the javascript format that I need:
{ tech: 'NAME', value: $array['NAME'][0] },
{ tech: 'NAME2', value: $array['NAME2'][0] },
{ tech: 'NAME3', value: $array['NAME3'][0] },
{ tech: 'NAME4', value: $array['NAME4'][0] },
...etc
Some type of loop would be preferred because the names can vary.
If it was just PHP I could do it, but I'm not too fluent in Javascript.
Could someone help me come up with a solution?
The good news is that you don't have to know much javascript. Create your data structure as you want it in php, and then use json_encode: http://php.net/manual/en/function.json-encode.php
<?php
$for_chart = array();
foreach($names as $key => $name){
$obj = new stdClass;
$obj->tech = $key;
$obj->value = $name[0];
$for_chart[] = $obj;
}
?>
the result is:
[{"tech":"NAME","value":1},{"tech":"NAME2","value":5},{"tech":"NAME4","value":9}]
You can use it in your javascript like this:
<script>
var my_names = <?=json_encode($for_chart)?>;
alert(my_names[0].value); // alerts "1"
</script>
http://sandbox.onlinephpfunctions.com/code/2682f09fd5515b220402db9c600b70a0501a87d9
If you json_encode the array you have, it comes out to:
{"NAME1":[16,12,4,0],"NAME2":[19,19,0,0],"NAME3":[31,29,2,0]}
which will give you a javascript object to iterate:
If you have the json object in a variable called arrayData:
var gridData = [];
for (var name in arrayData) {
var rowObj = { tech: name, value: arrayData[name][0] };
gridData.append(rowObj);
}
At the end of that, you will have an array of objects that should be what you're looking for in gridData.
If you would echo it in the following format you can JSON to get the data:
[{tech: 'NAME', value: $array['NAME'][0]},{tech: 'NAME', value: $array['NAME'][0]}]
In your js you could do something like the following:
var names = $.getJSON('http://localhost/index.php?name', function(data) {});
This way you have an array in js.
To get the javascript code just iterate over the php array an echo the json records like you want:
<?= foreach($array as $key => $value){
echo "{ tech: '" .$key ."', value: '" .$value[0] ."'},";
}
?>
//Assuming this is your array
$getArray["NAME"] = array(16,12,4,0);
$getArray["NAME2"] = array(19,19,0,0);
$getArray["NAME3"] = array(31,29,2,0);
$newArray = array();
foreach($getArray as $indKey=>$indArrVal) {
$newArray[] = array("tech"=>$indKey, "value"=>$indArrVal[0]);
}
echo json_encode($newArray);
here it is, create a new array, with the required indexes and then stringify it using json_encode
I have a number of coordinates stored in a sqlite database. I need these coordinates to be used in a heatmap on leaflet.
I'm using the following plugin: https://github.com/Leaflet/Leaflet.heat
The data needs to be in the following format:
var addressPoints = [
[52.344161, 4.912279],
[52.342425, 4.913038],
[52.342034, 4.913256],
[52.341987, 4.912462]];
I extract the data from the sqlite database in PHP using:
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
while ($row = $results->fetchArray()) {
echo json_encode($row['coord']);
}
$db->close();
The data retrieved looks like:
"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"
How can I get the SQLite data inserted in 'var addressPoints' in a correct manner?
Thansk in advance,
JWB
If the data follows that same format with the quotes at start and end and double quotes in between pairs the following should produce an array with the pair as an entry.
$data='"52.344161000, 4.912279000""52.342425000, 4.913038200""52.342034000, 4.913256000""52.341987000, 4.912462000""52.342336000, 4.912106000"';
$pairs=explode('""',trim($data,'"'));
print_r($pairs);
output:
Array
(
[0] => 52.344161000, 4.912279000
[1] => 52.342425000, 4.913038200
[2] => 52.342034000, 4.913256000
[3] => 52.341987000, 4.912462000
[4] => 52.342336000, 4.912106000
)
You could alter your initial php however which would produce different data
$db = new SQLite3('jwtrack.sqlite');
$results = $db->query("SELECT coord FROM trackjw");
$json=array();
while( $row = $results->fetchArray() ) {
$json[]=$row['coord'];
}
$db->close();
$json=json_encode( $json );
echo $json;
if you needed this without the quotes around the values...
$json=str_replace('"','',$json);
in the javascript then you could do:
echo "var addressPoints={$json};";
I'm loosing hairs on this.
I have an PHP array:
Array
(
[10-10-2015] => Array
(
[0] => Array
(
[hour] => 10:00
[title] => Meeting x
)
)
[10-09-2015] => Array
(
[0] => Array
(
[hour] => 17:00
[title] => another meeting
)
[1] => Array
(
[hour] => 11:11
[title] => other meeting
)
)
)
As you can see, there are two meetings in the same day.
That's correct.
I need to generate Javascript array:
var codropsEvents = {
'10-16-2015': ['<span>event one</span>', '<span>event two</span>'],
'10-17-2015': ['<span>event one</span>', '<span>event two</span>'],
};
Any help or suggestions how to do it ?
Use json.
echo 'var myJsArray = JSON.parse("'.json_encode($myPhpArray).'");';
You can use json_encode($array) in php to convert it to valid json string. In your javascript you can use JSON.parse(json) for parsing json string.
For example :
<?php
$array=array
(
'10-10-2015' => array
(
0 => array
(
'hour' => '10:00',
'title' => 'Meeting x'
)
)
);
?>
<script>
var data = JSON.parse('<?php echo json_encode($array); ?>');
// or var data = <?php echo json_encode($array); ?>;
</script>
Try this approach:
create array that You want:
<?php
$events = .....;
$data = [];
foreach($events AS $date => $eventsByDate) {
$data[$date] = [];
foreach($eventsByDate AS $event) {
$data[$date][] = '<span>'.$event['title'].'</span>';
}
}
?>
output $data array encoded as json string and parse it to get javascript object or array:
<script>
var codropsEvents = JSON.parse('<?=json_encode($data)?>');
console.log(codropsEvents);
</script>
New progress...
Without JSON.parse, only just:
var codropsEvents = <?=json_encode($events);?>
it's returning
var codropsEvents = {
"10-10-2015":[
{"time":"10:00","title":"Meeting X"}
],
"10-09-2015":[
{"time":"17:00","title":"Other event"},
{"time":"11:11","title":"Other Meeting"}
]
}
which causes returning Object
Any ideas ?