Group JSON using PHP - 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.

Related

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

Using JSON to get data from a PHP array

I've read similar questions here and attempted a few of the solutions with no luck.
I'm trying to use var jQuery_my_array = <?php echo json_encode($my_array); ?>; to convert.
I know this returns a valid array called jQuery_my_array, but I can't get the array contents properly.
I've also tried
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
var jQuery_my_array_parsed = JSON.parse(jQuery_my_array);
alert(jQuery_my_array_parsed[2]);
I'd like to just do something like alert(jQuery_my_array[2][0]); and get the strings I've stored in the php array.
Possible? I'm not a pro coder btw ;)
No need of JSON.parse
Try this
<?php
$my_array = array("sone"=>12, "sss"=>45);
?>
<script>
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
console.log(jQuery_my_array);
</script>
Output of the above will be Object {sone: 12, sss: 45}
You can use these as jQuery_my_array.sone;
If your php array is like $my_array = array(12, "sss", 45);
Then can use json as console.log(jQuery_my_array[0]);
The problem you are encountering is due to the fact that you are trying to json_encode an array of objects. In order to do this you will need to transform those objects into an array, which can be done by implementing the JsonSerializable interface:
class imageObject implements JsonSerializable {
// your object code
public function jsonSerialize() {
// one implementation. You could also only return those values you actually need
return get_object_vars($this);
}
}
then in your javascript:
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
console.log(jQuery_my_array_parsed);
Use console.log, not alert. To view the output of the console.log statement open your javascript console

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

How to get array from JSON?

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.

How to read php array of string in javascript

var longitudeArray = new Array(<?php $result = count($longitudeArray);
if ($result > 1){
echo implode(',', $longitudeArray);
} else {
echo $longitudeArray[0];
}
?>);
$longitudeArray contain array of number like: $longitudeArray = array(23.54545, 2323.32);
Above script create following javascript array:
var longitudeArray = new Array(12.32444,21.34343,23.5454);
but if i passes string in $longitudeArray like:
$longitudeArray = array('one', 'two');
instead of integer value in $longitudeArray then my javascript array is not creating properly or its not working.
Try
var longitudeArray=<?=json_encode($longitudeArray)?>;
If you pass an array of strings to your code, you will end up without quotes around them in your generated javascript code. You need to add some quotes somehow, something like:
var longitudeArray = new Array("<?php echo implode('","', $longitudeArray);?>");
#Shad, very useful and efficient approach. In the same manner, if one is trying to convert a PHP array to pass back to a JavaScript function (EG: an AJAX callback), that would be accomplished as such:
$some_php_array = array( 'indexA' => 'nice', 'indexB' => 'move' );
json_encode($some_php_array);
Where the PHP data would look as follows in JavaScript:
{"indexA":"nice","indexB":"move"}

Categories