How to get array from JSON? - php

I am trying to fetch data from MySQL table that have 2 columns, Temperature and Value. I want to store these values to JSON and then to pass to the client side script. My PHP code is:
database2json.php:
<?php
$con = mysql_connect("localhost", "root", "123456");
if (!$con) {
die('Could not connect:' . mysql_error());
}
mysql_select_db("klima", $con);
$result = mysql_query("select Dan, Temperatura from TEMPERATURA");
$niz = array();
while ($row = mysql_fetch_array($result)) {
$niz[$row['Dan']] = $row['Temperatura'];
}
mysql_close($con);
$obj = json_encode($niz);
echo $obj;
?>
When I run this file on server I get this:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
That is what is expected.
Html is nothing special.
index.html:
<html>
<head>
<title>jQuery</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<div id="id1"></div>
</body>
</html>
Now I call php from jQuery and to show these values.
custom.js:
$(document).ready(function(){
$.post('database2json.php', function(data){
$('#id1').html(data);
},
"json");
});
This also gives same output like php:
{"1":"-1","2":"0","3":"0","4":"0","5":"4","6":"5","7":"3","8":"2","9":"2","10":"1","11":"-2","12":"-2","13":"0","14":"1","15":"-2","16":"-1","17":"-1","18":"-2","19":"-1","20":"3","21":"-1","22":"0","23":"1","24":"3","25":"1","26":"1","27":"-1","28":"-1","29":"4","30":"5","31":"5"}
Now I dont know how to convert this into array of [Dan, Temperatura]. I need this array to forward to chart and plot data (I am not asking about plotting, just to get array).
How to achieve this?

Your output
{"1":"-1","2":"0","3":"0",...,"31":"5"}
Is a JavaScript object in its current form. You can simply access it as:
alert(data["1"]);
// -1
alert(data["31"]);
// 5
Note that the common syntax for object literals is dot notation: object.propertyname, but that will not work for numeric property names like your 1-31 indexes. So instead you use the bracketed property name as in data["1"].
If you really need it as an indexed array, you can convert it as:
var array = [];
for (key in data) {
array[key] = data[key];
}
// Now array is an Array with similar structure to the object data
Update
There is another possibility to get this data as a proper array directly from PHP. You can wrap the output in an additional array like this:
// Wrap the array in another array indexed as niz
$obj = json_encode(array("niz" => $niz));
echo $obj;

I have something like your code in my project. It is like this:
$final = array('msg' => $msg, 'result' => $result);
echo json_encode($final);
As you see, I made an array with 2 key and value. This code works fine for me. try to obey the method above to create your array and test it again. I hope you can solve your problem.

If I understand correctly, you want to convert PHP's JSON output to an actual array, right?
You can simply use eval() for that.
myArray = eval(data);
WARNING: Eval is considered unsafe and you should only use it for trusted sources. Make sure that there is absolutely no way for anything else than your PHP script to be evaluated.

Related

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Group JSON using PHP

This is my code
<?php
$something = array();
while ($row = mysql_fetch_assoc($result)) {
$something[] = $row;
}
mysql_close($con);
?>
<script type="text/javascript">
some= <?php echo json_encode($something); ?>;
</script>
The above code will generate:
[{"id":"1","title":"Ray","author":"Ray","thumb":"some source","views":"10000"}]
But I want to generate a json string like this:
[{"id":"1","title":"Ray","author":"Ray","image":{"cls":"image","thumb":"some source","views":"10000"}}]
Any help ?
json_encode encodes whatever object structure you have. If you want certain properties to be as sub-object, you have to create such object in memory..
For instance, if you had
$a = array("id"=>1,
"title"=>"Ray",
"image" =>
array(
"thumb"=>"some source",
"cls"=>"image"
)
);
it would encode in json in a similar way you are mentioning.
This means that you have to loop through mysql results and create the new structure before. Then call json_encode on it.

Getting PHP session array values into Javascript

I have stored array values in PHP session.
Now I want to retreive this array and convert it to javascript aray.
This is how I set PHP session:
var listone = ["one", "two", "three"];
function setSession(listone){
$.get(
"setSession.php",
{listone:listone}
);
}
So if once these values are set and I refresh the page, I check if the session has been set. If set, I want to do something like this:
<?php
session_start();
if(isset($_SESSION['listone']))
{
?>
listone = Array('<?php echo json_encode($_SESSION['listone']) ?>');
<?php
}
?>
When I do this, the 'listone' array is showing me like this:
listone[0] = [
listone[1] = "
listone[2] = o
listone[3] = n
listone[4] = e
listone[5] = "
.... etc
I know I am doing something wrong.
Is it the way I am storing the array in PHP session?
or
Is it the way I am retrieving it back to JS?
Thanks for any pointers. I am willing to dig more if guided properly :)
You may be trying to do one of two things here- either something to do with AJAX, which is expecting a JS response, or you're trying to access a session variable directly in JS.
If you simply wish to switch a PHP variable into a JS readable array, you can do:
json_encode($_SESSION['myarray']);
This would need to be a response readable & interpreted elsewhere by a JS script (e.g. an AJAX response).
PHP session variables arent accessable through JS directly, however, you can construct JS within PHP, wrapping the two together so you use PHP to output JS populated with the data held within your PHP session variable. The key here is the order of the code, and how your JS is structured- i.e. you will probably want to reference a global JS variable so the values are accessible by your other JS- or call a function etc...
So, you could have:
session_start();
if(!isset($_SESSION['myarray'])){
$_SESSION['myarray']=array('one', 'two', 'three');
}
echo "<script type='text/javascript'>
var myJSvariable = new Array();";
foreach($_SESSION['myarray'] as $key=>$value){
echo "myJSvariable[".$key."]=".$value.";";
}
echo "</script>";
Try to change your php file to this or a similar one
<?php
session_start();
$result = array();
if(isset($_SESSION['listone'])) {
$result['listone'] = $_SESSION['listone'];
}
echo json_encode($result);
?>
json_encode translate your array into a json array and you don't need to create a new one.
Plus I would put the required variables into an hash array and return just the json_encode of that array in order to have a cleaner code.

Passing a multidimensional PHP array to javascript

I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>

PHP array to JS array with jQuery and json_encode

I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).
An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Categories