This is a very basic question, so excuse my lack of knowledge.
I'm trying to output a JSON query from Freebase in PHP. I've already been able to parse the JSON into PHP using cURL and json_decode.
Here is a link to the JSON array (for some reason I can't get this to link directly):
http://www.freebase.com/api/service/mqlread?query={%20%22query%22%3A%20[{%20%22type%22%3A%20%22%2Fpeople%2Fperson%22%2C%20%22ns0%3Atype%22%3A%20%22%2Fbase%2Fbillionaires%2Fbillionaire%22%2C%20%22employment_history%22%3A%20[{%20%22company%22%3A%20null%20}]%2C%20%22name%22%3A%20null%20}]%20}
I'm able to ouput the first level of the array (Bill Gates), but not the 2nd level (Microsoft).
I've figured out how to display and loop through the people's names, just not their associated companies.
So my code, thus far, gets me a list of names.
$results = json_decode($response)->result;
foreach ($results as $name) {
echo $name->name . '<br/>';
I want the companies associated with each name to be displayed.
The browser-format should be:
Person 1 Name:
Company Name 1
Company Name 2
etc.
Person 2 Name:
Company Name 1
etc.
Thanks for any pointers--I'm sure that I'm just missing the simple way to structure the PHP code to display this easily.
How about:
$results = json_decode($response)->result;
foreach ($results as $person) {
echo $person->name . '<br/>';
foreach($person->employment_history as $employer) {
echo $employer->company . '<br/>';
}
echo '<hr />'; // horizontal rule for good measure
}
Related
I have a page setup so that its grabbing data from an external JSON about football/soccer matches, I am applying some extra data for a match report from a database table hosted by my website.
Within the json data I get the following three variables which i want to use:
$match['id']
$match['home-team']['name']
$match['away-team']['name']
In my database i have the following 4 data sets
id
gameid
author
matchlink
What i am trying to accomplish is using the json data to create a variable of the match['id'] into a variable for use like so.
$gameid_{$match['id']} = $match['home-team']['name'] ' vs ' $match['away-team']['name']
for example
if the match id was: 123456
if the home team name was: Town FC
if the away team name was: City FC
then i would get a variable like this:
$gameid_123456 = Town FC vs City FC
i have tried the following:
foreach ( $json_decoded as $match ) {
${$match['id']} = $match['home-team']['name']. 'vs' .$match['away-team']['name'];
}
global ${$row->gameid};
echo ${$row->gameid};
but it does not display anything.
Am i missing something or is that completely wrong?
Thanks in advance
Adam
Just incase anyone comes across this and would like further assistance I created a variable array, here is how the foreach code worked:
global $match_data;
$match_data = array ();
foreach ( $json_decoded_r as $match ){
$match_data[ $match['id'] ] = $match['home-team']['name']. ' vs ' .$match['away-team']['name'];
}
then whilst from the database which contains this variable which contains the gameid
global $match_data;
echo $match_data[ $row->gameid ];
So for instance with my json echoing out the $match_data[367327] resulted in Aveley vs Hastings United
I have this JSON output from a Government API, I need to display it using PHP. The problem is I can't use foreach more then once in a row or it doesn't work. I can't load all the criteria into the first foreach because say the first piece of data ACASS returns 3 results, all the fields after it will be displayed 3 times. Each field could return 1-10 results so there needs to be a system that accounts for variables.
I'm thinking the solution is to put all of the JSON items I need displayed into the first foreach but set them to only display if they're populated. That or use the current coding system I have but account for variable numbers somehow.
Any potential solutions are greatly appreciated.
This is the JSON output... https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY
Here's the PHP I'm using...
echo "ACASS ID:".$decoded_results['sam_data']['registration']['qualifications']['acass']['id']."</br>";
foreach($decoded_results['sam_data']['registration']['qualifications']['acass']['answers'] as $acass)
{
echo 'Answer Text:'.$acass['answerText'].'</br>';
echo 'ACASS Section:'.$acass['section'].'</br>';
}
$formerfirm = $decoded_results['sam_data']['registration']['qualifications']['acass']['answers'][2]['FormerFirm'];
echo 'Former Firm ID:'.$formerfirm['id'].'</br>';
echo 'Former Firm Year Established:'.$formerfirm['yearEstablished'].'</br>';
echo 'Former Firm Name:'.$formerfirm['name'].'</br>';
echo 'Former Firm DUNS'.$formerfirm['duns'].'</br>';
I did my best to keep this short and simple question / code wise. In summary the issue is if you look at the JSON the data hierarchy makes a lot of the information display under ACASS/Answers and then the next category. I never know how many responses there will be and I'm not sure how to account for those variables.
I would like to thank everyone on these boards who has guided me as a new member and helped me post cleaner, more concise questions. Also thank you to everyone who has taken their own personal time to help me learn to become a better programmer.
use a tool like http://jsonviewer.stack.hu/ for visualizing your json structure. It helps a lot.
<?php
$url = "https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY";
$contents = json_decode(file_get_contents($url));
// echo var_dump($contents);
$sam_data = $contents->sam_data;
// echo var_dump($sam_data);
$registration = $sam_data->registration;
//echo var_dump($registration);
$acass = $contents->sam_data->registration->qualifications->acass;
$id = $acass->id;
echo "id: ". $id . "<br />";
//echo var_dump($acass->answers);
foreach($acass->answers as $answer) {
if(isset($answer->FormerFirm)) {
$formerFirm = $answer->FormerFirm;
echo var_dump($formerFirm);
}
}
Okay so, first of all, I searched through the www for this question, and I found some question related to arrays but not exactly to mine.
Okay so as you may know, paypal only allows one custom variable to be $POST but I need to gather the product id AND the quantity of the item bought. So to do this I made my custom variable into something that would get the post like (25-1,12-3,13-4) it means, the user bought 3 items(separated by commas), where the first number is the product id (then the separator '-' comes in) and the second one is the quantity. (so they're all in the same row and column)
Now my problem is displaying it from the database. I need to get the product name and details that's why I need to separate the numbers from each array as a string and fetch the data from the database for the information of the product. (I'm using an older version of php anyway, 5.2, I guess.)Now the problem is:
1.) It returns the word 'Array' (literally) so it would say like ArrayArrayArray
2.) How do I explode/separate those data so I can get it because I need the product ID to fetch some other data... I tried exploding it into array, then exploding it again but doesn't work (most likely my code is wrong?)
Here is my code: (I've already connected to the database)
$data = mysql_query("SELECT * from transactions") or die(mysql_error());
/* My table tag and headers goes here */
while($info = mysql_fetch_array( $data )) {
echo "<tr>";
echo '<td>' . $info['id'] . '</td>';
echo "<td>";
$array = $info['product_id_array'];
$explode_array = explode(",", $array);
foreach($explode_array as $explode_more){
$explode_more = explode("-", $explode_array);
$prod_id = $explode_more[0];
$quantity = $explode_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
echo"</td>";
echo"<tr>";
}
If only paypal would allow multiple custom variables T_T Thank you guys. Forgive me if I can't express my question very well or my language is not good, as english is not my first language :), Good day!
Your variable names are mixed up. Inside the foreach-loop, you should do something like this
foreach($explode_array as $explode_more){
$explode_even_more = explode("-", $explode_more);
$prod_id = $explode_even_more[0];
$quantity = $explode_even_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
Note, that $explode_more is used inside the loop and $explore_array is left as is.
Separate this in multiple tables, never store non-atomic values in 1 column.
Certainly not when they have relation with another table.
Suppose you want to know the sales from a certain product in some period.
I've been trying to figure out how to split the array and add different titles for each of the separate titles on the page, for each of the different things that this displays. However the most I can manage to do is add a comma between the numbers and words.
I would like to add selling"1st variable price"second variable" etc however I don't quite know how to do anything other than to turn this very confusing looking bunch of letters:
user name and notes 01001000013972583957ecCCany amount-w378- v west
into anything other than this:
0,100,10000,1397258395,7ec,CC,any amount-w378- v west
Also, this is what it looks like in its JSON form:
{"selling":"0","quantity":"100","price":"10000","date":"1397258395","rs_name":"7ec","contact":"CC","notes":"any amount-w378- v west"}
I just want all the information that is in there to displayed like that however I'm not quite sure how to add the titles that is in the JSON data. I also don't have access to the external site to change anything.
A little background: what I am trying to achieve is a price look-up for a game on my website from an external site. I tried to use an iframe but it was terrible; I would rather just manually display it rather than showing their site from mine - their style and my style clash terribly.
$json = file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe');
$obj = json_decode($json,true);
$blah1 = implode( $obj[0]["offers"][1]);
print_r($blah1);
If you know where it is, you should be able to just grab it and show it out?
You can use a failsafe to check if it is present with is_array() and isset() functions - see php.net docs on them.
Your print_r should give you good valid info -- try to wrap it around <pre></pre> tags before for better readability or view the source - it will be easier!
<pre><?php print_r($obj) ?></pre>
This should be your starting point, and from here you will either take the first one of your items or loop through all with
foreach ($obj as $o) { //should be $objects, not $obj
//do whatever with $o, like echo $o['price']
}
Each offers row is a table with each field separated by row:
$item = json_decode(file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe'));
while ($offer = array_shift($item[0]->offers)) {
echo "<table>" . PHP_EOL;
foreach ($offer as $field => $value) {
echo "<tr><th>$field</th><td>$value</td></tr>" . PHP_EOL;
}
echo "</table>" . PHP_EOL;
}
http://codepad.org/C3PQJHqL
Tables in HTML:
http://jsfiddle.net/G5QqZ/
I have following code:
SELECT q21, q21coding AS Description FROM `tresults_acme` WHERE q21 IS NOT NULL AND q21 <> '' ORDER BY q21coding
It brings back the following (excerpt):
Text Description
Lack of up to date equal pay cases&legislation - t... Content needs updating
The intranet could contain more "up to date traini... Content needs updating
Poorly set out. It is hard to find things. Difficulty in navigating/finding content
Only use the intranet as a necessity. Will ask my ... Difficulty in navigating/finding content
Now, I'd like to display this in a table on a PHP page but am having some problems because of the way I'd like it displayed, it needs to be as follows:
Content needs updating
----------------------
[List all the comments relating to this description]
Difficulty in navigating/finding content
----------------------------------------
[List all the comments relating to this description]
and so on.
Now I think it is a For Each loop in PHP but I am having terrible difficulty getting my head around this - any ideas and suggestions very very welcome!
Thanks,
Simple approach
Set prev_desc to NULL
For each row print text
If description is not equal to prev_desc prepend with the description for the new "section" and set prev_desc <- description
E.g.1 (untested!),
$prev_desc = null;
while ($row = mysql_fetch_assoc(...)) {
if ($prev_desc != $row['description']) {
print '<h1>' . $row['description'] . '</h1>';
$prev_desc = $row['description'];
}
print $row['text'] . '<br />'; // Formatting needed
}
Note: You must keep the ORDER BY <description-column> in order to have rows "grouped". Otherwise this simple approach will not work.
Less presentation-specific approach
I could be considered more "clean" to create some kind of 2D container to "categorize" the extracted data, e.g.,
$items = array(
'Content needs updating' => array(
'Lack of ...',
'The intra...'
),
...
);
You could then loop over these items like so1:
foreach ($items as $desc => $texts) {
print '<h1>' . $desc . '</h1>';
foreach ($texts as $text) {
print $text . '<br />';
}
}
1 As #bobince has noted, make sure that content going directly into the final HTML is properly escaped, see e.g. htmlspecialchars().
You just need to keep track of which heading you last displayed. I don't know which library you're using for database access, so the details of how you access columns/rows will be slightly different, but here it is in kind-of pseudocode:
$lastHeading = '';
foreach($rows as $row)
{
if ($lastHeading != $row['Description'])
{
if ($lastHeading != '')
echo '</ul>';
$lastHeading = $row['Description'];
echo "<h1>$lastHeading</h1>";
echo '<ul>';
}
echo '<li>'.$row['Text'].'</li>';
}
if ($lastHeading != '')
echo '</ul>';
This has the added feature of putting comments in a <ul>, not sure if that's required for you or not.
This works because you've sorted by the "description" column. That means you know that all of the rows with the same "description" will come together.
you can either create multiple queries for each of the sections or loop over the data multiple times and filter based on the type of description using php.
$descriptions = array('Content needs updating','Difficulty in navigating/finding content');
$rows = <fetch all rows from the query>;
foreach($descriptions as $description)
{
echo '<h1>',$description,'</h1>';
foreach($rows as $row)
{
if ($row['description'] == $description)
{
echo $row['text'],'<br />';
}
}
}