generating javascript array from php - javascript

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 ?

Related

How to remove double quotes from a JSON response in javascript? [duplicate]

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);

PHP Array key value next to each other to use in javascript

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]]

Passing nested PHP loop to javascript

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

how to convert array from php into js

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.

Read JSON returned by PHP in Javascript

I want to select some content from the database and return it to the javascript. There are several rows returned by the database. I tried this with JSON and also get a result, if I print it out. But if I want to convert the JSON string, there is always the error message below. (at the JSON.parse) So, I assume maybe an mistake while filling the array? Thanks in advance guys!
Javascript:
$.ajax({
url: "./select_firsttracks.php",
type: "post",
success: function(resultset) {
$("#erroroutput").html(resultset);
var arr = JSON.parse("{" + resultset + "}"); // --> "Uncaught SyntaxError: Unexpected token {"
},
error: function(output) {
$("#erroroutput").html("fatal error while fetching tracks from db: " + output);
}
});
PHP:
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
echo json_encode($storage);
}
Output on the console:
[{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"}][{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"},{"id":"2","trackname":"no","artist":"Prinz Pi","genre":"Rap","url":"ftp:\/development","musicovideo":"1"}]
echo the json after the while
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
and change:
var arr = JSON.parse(resultset);
You're adding curly braces in front and behind your received JSON, here:
var arr = JSON.parse("{" + resultset + "}");
Phps json_encode returns perfectly valid JSON by itself. Try it without adding the braces:
var arr = JSON.parse(resultset);
The resulting json string is not valid, you can check it with jsonlint
Modify your php code to echo outside the loop:
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
And in javascript just use the output as a javascript object
success: function(resultset) {
console.log(resultset)
resultset.each(function(index,element){ console.log(index,element )})
},

Categories