Parsing JSON in PHP - php

I´ve got the following JSON string:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}},"recipes_id":{"ranking_1":"9","ranking_2":"10","ranking_3":"7","ranking_4":"5"}},"Message":null,"Code":200}
How can I parse it in PHP and extract a list of TITLEs?

You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:
$data = json_decode($json, true); // yields associative arrays instead of objects
foreach ($data['Data']['Recipes'] as $key => $recipe) {
echo $recipe['TITLE'];
}
(Sorry I can't actually run this code right now. Hope it helps anyway.)

If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:
var jsonData = {
"Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
// more data
};
alert(jsonData.Data.Recipes.Recipe_5.TITLE);
This will print the TITLE of Recipe_5 in a message box.
EDIT:
If you want all the titles in a list, you can do something like this:
var titles = [];
for (var key in jsonData.Data.Recipes) {
var recipe = jsonData.Data.Recipes[key];
titles.push(recipe.TITLE);
}
alert(titles);

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.

read jquery array in php

i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}

How to get and parse data from geocode farm

I am trying to get my website to get the json from the geocode farm api. I know how to contstruct the address where the api is but I don't know how to get the data back and parse and then display it in a javascript alert.
If you can help me do that, I will be very grateful.
Getting useful data out of the JSON response
Once you have a working URL that dumps the required JSON data, it's very easy. PHP offers built-in functions for processing and dealing with JSON data. In this case, you want to decode the JSON data into a usable format, such as an array or object.
Converting the JSON response to an array
To get it into an array, you can simply do:
$arr = json_decode(file_get_contents('http://example.com/foo.json'), 1);
Knowing the structure of the array
Now in order to work with the array, you will have to know how it is structured. For that purpose, you can use the debugging function print_r():
echo '<pre>' . print_r($arr, 1) . '</pre>';
Traversing the array to extract information
Once you know the structure of the JSON data, you can traverse it using a foreach loop:
foreach ($arr as $key => $value) {
// Do more stuff with $value
}
You can make a request with PHP, for example using file_get_contents() and then echo the result into JavaScript. You can then use JavaScript to extract the information you need and generate an alert.
Simplified example:
<?php
$url = 'http://api-url...';
$response = file_get_contents($url);
$data = json_decode($response, true);
$coordinates = $data['geocoding_results']['COORDINATES'];
?>
<script>
var coordinates = <?php echo json_encode($coordinates); ?>;
alert(coordinates.latitude + '; coordinates.longitude);
</script>

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

Passing two arrays in a jQuery .post() , how do I catch this data in PHP and use it there?

I'm making a jQuery .post() with the following arrays:
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray
The data inside these arrays:
cleanedPermaLinkArray looks like this: ["2012","10","30","hello-world"]
and cleanedLinkStructureArray like this: ["year","monthnum","day","postname"]
Javascript code:
var ajaxPost = $.post(
enableAJAX.ajaxurl,
{ action: 'ajaxRequest',
'ajaxRequestNonce' : enableAJAX.ajaxRequestNonce,
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray },
'json'
);
ajaxPost.done(function(responseText) {
alert(responseText);
console.log(responseText);
});
ajaxPost.fail(function() {
alert("Oops, I'm afraid we've broken something");
});
I don't understand how I catch the two arrays in PHP? and use the data from the arrays inside PHP? Preferably I would create new PHP array with them, where the values inside cleanedLinkStructureArray become the keys for the array and the values inside cleanedPermaLinkArray the values for that new array.
I guess it must be something with this, but I need someone more experienced to tell me what I need to do here.
$_POST['cleanedPermaLinkArray[]']
$_POST['cleanedLinkStructureArray[]'];
Any help would be appreciated.
Kind regards,
Marnix
Your arrays will be in
$_POST['cleanedPermaLinkArray']
$_POST['cleanedLinkStructureArray'];
you can do a simple var_dump($_POST) to see how the data is formed
First, in $.post, you do not need the square brackets, so this is one of your params:
'cleanedLinkStructureArray': cleanedLinkStructureArray,
Then in PHP, you have to first catch it like such:
$cleanedLinkStructureArray = $_POST["cleanedLinkStructureArray"];
Now, you can use the following:
foreach ($cleanedLinkStructureArray as $item) {
// Do something with $item
}
Another way is to pass all your params from $.post to php is setting them as json object.
This is all coming down from the server as JSON, right? Just use json_decode on the values and the'll be converted to arrays, natively inside of php.
$cleanedPermaLinkArray = json_decode($_POST['cleanedPermaLinkArray[]']);
echo cleanedPermaLinkArray[0]; // some value..

Categories