Retrieve value from a Json Array - php

I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:
Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1
The code that achieves this is as follows:
$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";
$post_data_response = file_get_contents($post_data_URL);
$a_post_data_array=json_decode($post_data_response);
I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.
echo "**** -- " . $a_post_data_array[post_title] . "<br>";
Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.

There are multiple issues with your code:
First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
Then the result array is a list, and you have to access the first element as $data[0]
The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.)
And you need to put those array keys in quotes, like print $data[0]["postTitle"];
Turn up your error_reporting level for some development help.

echo "** -- " . $a_post_data_array[0]['post_title'];

try this PHP code:
//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);
// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');
// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";

Related

Loop through json decoded array in PHP

I have data in Json format which i have decoded into a php array which when printed produces the following (just a snippet of the information).
Array (
[Title] => Array([Heading] => Company Name [Info] =>)
[SubTitle] => Array([Heading] => Welcome to Company Name[Info] =>information on the company)
)
my question is how do I loop through this information and print the title and then print the value.
I have tried the following which prints all the data at one time
foreach($data['SubTitle'] as $key => $value){
echo $value;
}
And then i tried this just to print the info section which i thought might work but instead throws an illegal string offset error
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
I can get the information from the Title array as it is straight forward as it only has data value in the heading. However i would like the output from the Subtitle array to print the heading and info like below:
Welcome to Company Name
Information on the company
I thought this would be straight forward but it is turning out much more difficult than expected and has taken up a lot of time so any help would be greatly appreciated.
So I am going to assume you have a JSON string that looks like this:
$json = '{"Title":{"Heading": "Company Name", "Info": null}, "SubTitle": {"Heading": "Welcome to Company Name", "Info": "information on the company"}}';
visualised, looks something like this:
So, if you've decoded this json into an associative array:
$result = json_decode($json, true);
Then, in order to access the data, you don't need to "loop" over it; all you need to do is:
echo $result['Title']['Heading']; // will print 'Company Name'
echo $result['Title']['Info']; // will print nothing, as it is empty
echo $result['SubTitle']['Heading']; // will print 'Welcome to Company Name'
echo $result['SubTitle']['Info']; // will print 'information on the company'
Hope this helps. This is basic php, please look into the following reading materials:
https://www.php.net/manual/en/function.json-decode.php
https://www.w3schools.com/php/php_arrays.asp
Change your code, from this:
foreach($data['SubTitle'] as $key => $v){
echo $v['Info'];
}
To this:
foreach($data['SubTitle'] as $v){
echo $v . "<br/>"; // the <br/> makes a new line
}
Output will be:
Welcome to Company Name
Information on the company
$v is no longer an array in foreach, it becomes a variable.
Some information about html tags: https://www.w3schools.com/tags/
Also see how loop works: https://www.guru99.com/php-loop.html

problems with JSON Decode & strings

having a bit of an issue here. I'm passing data over an AJAX command to my php script. The data travels across fine.
Print_r
Array
( [0] => stdClass Object
( [Loc] => Main Door
[Module] => O2
[Dect] => O2
[GasDec] => O2
[ScB4] =>
[ScA4] =>
[A1] =>
[A2] =>
[CalGas] =>
[CalGasA] =>
[Factor] =>
[ZB4] =>
[ZA4] =>
[CalB4] =>
[CalA4] =>
[CHNoID] => 5
[JobID] => 3 )
)
I can use The following method just fine but when i use option two it doesn't like it due to this error message:
Catchable fatal error: Object of class stdClass could not be converted to string
Methods
//Method one
echo "JobID: " . $comm[0]->JobID; // result: 3
//Method two
echo "JobID: '$comm[0]->JobID'"; // get error message
The reason im using method two is so I can pass the information into mysql. If anyone knows something i'm missing or it can't be done or even a easier way. please say.
Thanks.
EDIT
Query
$sql = "INSERT INTO
calinfo (Sbefore, Safter, A1, A2, CalGas, Factor, Zbefore, Zafter, Cbefore, Cafter, SysInfoID)
VALUES
('$comm[$i]->ScB4', '$comm[$i]->ScA4', '$comm[$i]->A1', '$comm[$i]->A2', '$comm[$i]->CalGasA', '$comm[$i]->Factor', '$comm[$i]->ZB4', '$comm[$i]->ZA4', '$comm[$i]->CalB4', '$comm[$i]->CalA4', '$comm[$i]->CHNoID');";
$sql .= "UPDATE
jobs
SET
CompletedBy = $tech
WHERE JobID = '$comm[$i]->JobID';"; //<-- when i try the method of "WHERE JobID = ".$comm[$i]->JobID.";"; it doesnt like it...
You may need to do as
echo "JobID: '{$comm[0]->JobID}'";
So in the query u can use it as where some_col = '{$comm[0]->JobID}'
Try like this
$sql .= "UPDATE
jobs
SET
CompletedBy = $tech
WHERE JobID = '".$comm[$i]->JobID."'";
As the error message saies, the return cannot be converted to fit into a string directly.
echo sprintf( "JobID: '%s'",$comm[0]->JobID);
or
echo "JobID: '{$comm[0]->JobID}'";
or
echo "JobID: '" . $comm[0]->JobID . "'";
should do the trick
Simple double quotes won't interpolate complex combinations like this. You need to use curly braces to achieve this, e.g. echo "JobID: {$comm[0]->JobID}";.
You could however also use printf, e.g. printf("JobID: %s", $comm[0]->JobID);.

Extraing data from json array and separate according to type

So I am currently trying to extract information from a json array using json_decode($result,true). The background here is that there is another php script getting information from a database and it is sending the data to me as json_encoded result.
using print_r($json) i get the following
Array
(
[result] => 1
[message] => Query Successful
[data] => Query Output
[0] => Array
(
//Several values
[test] => test
[Example] => catcatcat
[choice2] => B
)
[1] => Array
[test]=> test
//etc....
I understand we can use a simple for loop to get some stuff to display or in this case I used
for($i=0;$i<=count($json); $i++){
echo $json[$i]['test'];
//etc etc
}
and that will display the value. But what I cant figure out is how to send that to my HTML page as an output as a list.
I am trying to get it to display as following
Test catcatcat B
Test etc etc
--This may be a separate question but for me to learn I want to know if it's possible to actually break down the array and send to html as radio input and turn it into a value to choose from.
Your JSON result is a mixture of 1st level elements and sub-arrays, so you'll need to filter those.
Use a foreach loop like this to output radio buttons:
foreach($json as $current) {
if(!is_array($current))
continue; // skip top level properties that aren't sub arrays
echo '<input type="radio" name="yourradio" value="' . $current['choice2'] . '"> ' . $current['test'] . ' ' . $current['Example'];
}
The value of the radio button and the labels are up to you, but that's the general idea.

Return A Single Variable From Array

i am using following script:
http://www.micahcarrick.com/php-zip-code-range-and-distance-calculation.html
To get the details for a ZIP code, I am using this:
$selected = $z->get_zip_details($zip);
$result = implode(",", $selected);
echo $result;
This returns all details of "$zip" :
32.9116,-96.7323,Dallas,Dallas,TX,Texas,214,Central
Could any1 help me to make the script return ONLY the city variable? The FAQ of the script, says the following:
get_zip_details($zip)
Returns the details about the zip code: $zip. Details are in the form of a keyed array. The keys are: latitude, longitude, city, county, state_prefix, state_name, area_code, and time_zone. All are pretty self-explanitory. Returns false on error.
Unfortunately I cant figure out how to get a single value (city). Would appreciate any help!
Thanks!
The functions is returning an array, so we have to store it in a variable.
$selected = $z->get_zip_details($zip);
Next, we can select the key which points to the city. The key is also called city.
echo $selected['city'];
Change this line
$result = implode(",", $selected);
To
$result = $selected['city'];
For future reference, implode() explode() etc. are array functions. So, if you're using them on something then you can print_r() it to see its structure.
If you had done print_r($selected); or var_dump($selected);, you would have gotten something like this as output:
Array ( [x] => 32.9116 [y] =>-96.7323 [city] => Dallas [state] => Texas [etc] => etc )
So you can see the keys of the array to know how to access the individual values.

Php $_GET issue

foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan&region=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.

Categories