php array to 2d Javascript array - php

I'm working on passing 2 fields of SQL through php to javascript. I have read many tutorials on how to create a multidimensional javascript array. Where I get confused is how to code from php to javascript. I have seen a couple of tutorials on how to get the php data to javascript, but none on how to do this with 2 dimensions.
My first hangup is that if I'm creating a multidimensional array I need to count the number of records in my sql data before I declare the java array right?
update:
I got the data to JSON format as suggested below. Is there a way for me to get all of the contents printed to the web page so that I can see them and then narrow down what is displayed?
update III:
code:
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$new_row = array();
$new_column = array();
while($info = mysql_fetch_array($data)){
foreach( $info as $row_num => $row)
{
$thisItem = $row;
$new_row[] = $thisItem;
}
array_push($new_column = $new_row);
}
$json = json_encode($new_column);
echo $json;
?>
Working code:
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row['userID'],$row['date'],$row['lat'], $row['longi'], $row['alt']);
$json = json_encode($aData);
echo $json;

Fill a PHP array first, it's easier than building the string for a javascript array. Then - as ThiefMaster said as comment - use JSON to make the javascript array.

In PHP, you can use JSON PECL extension
<?php
$arr = array( 1=>array(3,4),
2=>array(4,5));
$json = json_encode($arr);
echo $json;
?>
Output
{"1":[3,4],"2":[4,5]}
In Javascript
var obj = JSON.parse('{"1":[3,4],"2":[4,5]}');
for(var i in obj){
for(var j in obj[i]) {
console.log(obj[i][j]);
}
}
JSON.Parse is for Gecko (Firefox alike), for cross-browser javascript JSON parse check jQuery.parseJSON or https://stackoverflow.com/search?q=json+parse+javascript
Sample implementation in PHP/jQuery, would be something like this:
json.php
$arr = array( 1=>array('Name', 'Age'),
2=>array('Fares','18'));
$json = json_encode($arr);
echo $json;
json.html
<html><head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$.getJSON('json.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>

Related

PHP retrieve data from db in multi queries and print json [duplicate]

Right now I have this PHP:
$columns = array(*/Data*/);
echo json_encode($columns);
And this is sent through an AJAX GET request with JQuery.
var columns = jQuery.parseJSON(response);
I would like to be able to send more than one array in the json_encode() is there any way to do this and how would you parse it with jQuery?
Sure, you could send an array of array. PHP associative array will become a javascript object.
In PHP:
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
echo json_encode($data);
and then on jQuery
var data = jQuery.parseJSON(response);
then you could then do something like this to access the values
console.log(data.fruits[0]); // apple
console.log(data.animals[1]); // elephant
The code should be like the following:
$columns = array(/*Data*/);
$columns1 = array(/*Data1*/);
echo json_encode(array($columns,$columns1));
in jQuery use
var columns_array=jQuery.parseJSON(response);
columns=columns_array[0];
columns1=columns_array[1];
$data1 = array();
$data2 = array();
$data1[] = array('apple','banana','cherry');
$data2[] = array('dog', 'elephant');
echo json_encode(array($data1,$data2));
in ajax,
console.log(response[0][0])//apple
console.log(response[1][0])//dog.....
After you have populated all the arrays namely $array1_json, $array2_json etc in my case,
$number_of_array1elements = count($array1_json);
$number_of_array2elements = count($array2_json);
$number_of_array3elements = count($array3_json);
array_unshift($array1_json , $number_of_array1elements);
// pushes element to the start of array1_json
array_unshift($array2_json , $number_of_array2elements);
array_unshift($array3_json , $number_of_array3elements);
and similarly for other arrays.
echo json_encode( array_merge($array1_json, $array2_json, $array3_json) );
In your .js file, use:
var val = xmlhttp.responseText;
var jsonData = JSON.parse(val);
var number_of_array1elements = jsonData[0];
for (var i = 1; i <= number_of_array1elements; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}
var number_of_array2elements = jsonData[i];
for ( i = i+1; i <= number_of_array1elements+number_of_array2elements+1; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}

Returning an array from a PHP query

I query my database with a PHP script that looks like this:
$query = "SELECT * FROM JKFactory WHERE ronde = '$ronde' AND moment = '$moment' AND klas = '$klas'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['afzetAG'];
echo ",";
}
This gives a result something like this:
10000,20000,30000,
I need this data to build a piegraph with chart.js.
chart.js works with arrays for the data. So the numbers should be returned as an array which I can put into an JavaScript variable which I can use with chart.js.
Another problem is the last comma. I have no idea how I can get rid of this comma.
Maybe these question are straightforward but I am relatively new in this field I really get stuck on this part.
You have the array and you'd put the comma after the results yourself. so try to declare an array like $arr before while and use array_push($arr,$row['afzetAG']) inside the while
To print your result like 1000,2000,3000... You can save the content into an Array and print it using implode:
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
echo implode(",",$data);
But if you want to use an Array from PHP to JavaScript you can do this:
<script type="text/javascript">
<?php
$data = array();
while($row = mysql_fetch_array($result))
{
array_push($data, $row['afzetAG']);
}
?>
var obj = <?php echo json_encode($data); ?>;
</script>
So now obj contains the Array ready to use in your JavaScript code.
$types = array();
while(($row = mysql_fetch_assoc($result))) { $types[] = $row['type']; }
ok i made it. To echo the result i used this:
$a = array();
while($row = mysql_fetch_array($result))
{
$b = $row['afzetAG'];
array_push($a,$b);
}
echo implode(",",$a);
This gives not an array i can use in javascript. In javascript i put the result in a variable myResult and than i used:
myResult = myResult.split(',');
this i could use in chart.js to build a pie chart.
Thanks guys. Now i can sleep.

How can I display JSON data using PHP

I have already created a dynamic JSON file.
My code is:
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro)) {
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
How can I get data from the JSON file? Using a while loop or anything similar?
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($res))
{
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
First, you have mistake on line 2
mysql_fetch_array($res)
AND NOT
mysql_fetch_array($respro)
Second, Use file_get_contents and json_decode functions
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
Thanks
This is how you see the posted json data in your php file.
I would prefer that:
$json_string=json_encode($records);
you must put the header
header('Content-Type: application/json;charset=utf-8');
and other side
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
First of all the way you are writing to the file inside the while loop is wrong.. Because you are unneccesarily calling the file_put_contents() again and again which is simply degrading your code performance..
So rewrite your code to this..
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro))
{
$records[]= $rowpro;
}
file_put_contents("product_file.json",json_encode($records));
To read the JSON data , make use of file_get_contents()
Like this..
$jsonData = file_get_contents("product_file.json");
echo $jsonData; //<--- Prints your JSON
In PHP ,
header('Content-Type: application/json;charset=utf-8');
$str = file_get_contents('product_file.json');
$jsonData = json_decode($str, true); //json decode
And in jquery you can use jQuery.getJSON example ,
$.getJSON( "product_file.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

parse json in javascript

I load a php/json file. This is my json file:
echo '{';
echo '"position":[';
while($inhoud = mysql_fetch_array($result))
{
echo '{';
echo '"lat":"'.$inhoud['lat'].'",';
echo '"long":"'.$inhoud['long'].'",';
echo '}';
}
echo ']}';
This works. I want to load it in my javascript and do it like this:
$.getJSON('req/position.php', function(data) {
$.each(data, function(key, val) {
newLatLng = key;
});
});
but this doesn't work. It loads the file but i don't get this data. What should i do?
Thanks,
I think you have some syntax errors in the JSON output.
When you output "long" data, you append a comma , at the end, but you should not, because "long" is the last key of the object.
You print out an object in a while cycle. These objects are part of an array. So, except for the last one, you have to append a comma , after the closing }.
And, if I can ask, why you are not using the json_encode() PHP function, instead of build all the JSON string manually? With it, you build all the data as normal PHP array, and then encode (translate) it in JSON. You will avoid all these annoying syntax stuffs.
Just try it:
$data = array();
$data['position'] = array();
while($inhoud = mysql_fetch_array($result))
{
$data['position'][] = array(
"lat" => $inhoud['lat'],
"long" => $inhoud['long']
);
}
echo json_encode($data);
You have your co-ordinates defined in the array named position. You need to iterate through that. The Array contains objects with the properties lat and long. If you want to use the values, you should try something like:
$.getJSON('req/position.php'), function(data){
$.each(data.position, function(index, value){
var newLatLng = { latitude: value.lat, longitude: value.long };
});
});
Return proper header in PHP script
header('Content-type: application/json');
And it should work.
Also use json_encode to encode PHP values into valid JSON.
Constructing JSON in php through strings works but is primitive. Start constructing an array and use json_encode().
$arr = array();
while($inhoud = mysql_fetch_array($result)){
$temp = array();
$temp['lat'] = $inhoud['lat'];
$temp['long'] = $inhoud['long'];
$arr[] = $temp;
}
echo json_encode($arr);
If all that you select in your mysql query is 'lat' and 'long' you could also just place $inhoud into $arr inside your while loop like so.
while($inhoud = mysql_fetch_array($result)){
$arr[] = $inhoud;
}
If you do this just make sure you only select columns in your mysql query that you would want to output in JSON.
$.getJSON('req/position.php', function(data) {
var obj = JSON.parse(data);
// At this point, obj is an object with your JSON data.
});
Source: MDN

Is there a way to pass multiple arrays to PHP json_encode and parse it with jQuery?

Right now I have this PHP:
$columns = array(*/Data*/);
echo json_encode($columns);
And this is sent through an AJAX GET request with JQuery.
var columns = jQuery.parseJSON(response);
I would like to be able to send more than one array in the json_encode() is there any way to do this and how would you parse it with jQuery?
Sure, you could send an array of array. PHP associative array will become a javascript object.
In PHP:
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
echo json_encode($data);
and then on jQuery
var data = jQuery.parseJSON(response);
then you could then do something like this to access the values
console.log(data.fruits[0]); // apple
console.log(data.animals[1]); // elephant
The code should be like the following:
$columns = array(/*Data*/);
$columns1 = array(/*Data1*/);
echo json_encode(array($columns,$columns1));
in jQuery use
var columns_array=jQuery.parseJSON(response);
columns=columns_array[0];
columns1=columns_array[1];
$data1 = array();
$data2 = array();
$data1[] = array('apple','banana','cherry');
$data2[] = array('dog', 'elephant');
echo json_encode(array($data1,$data2));
in ajax,
console.log(response[0][0])//apple
console.log(response[1][0])//dog.....
After you have populated all the arrays namely $array1_json, $array2_json etc in my case,
$number_of_array1elements = count($array1_json);
$number_of_array2elements = count($array2_json);
$number_of_array3elements = count($array3_json);
array_unshift($array1_json , $number_of_array1elements);
// pushes element to the start of array1_json
array_unshift($array2_json , $number_of_array2elements);
array_unshift($array3_json , $number_of_array3elements);
and similarly for other arrays.
echo json_encode( array_merge($array1_json, $array2_json, $array3_json) );
In your .js file, use:
var val = xmlhttp.responseText;
var jsonData = JSON.parse(val);
var number_of_array1elements = jsonData[0];
for (var i = 1; i <= number_of_array1elements; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}
var number_of_array2elements = jsonData[i];
for ( i = i+1; i <= number_of_array1elements+number_of_array2elements+1; i++ )
{
// use jsonData[i] to select the required element and do whatever is needed with it
}

Categories