Creating a variable from json data in PHP - php

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

Related

Simple Dom HTML tags without attributes

Hello I am trying to pull back roster information from ESPN.com. Each team's roster is saved into a table. I am trying to figure a way to save each tag into a variable as appropriate however each tag does not have an ID such as "jersey_number"/"player_name" so search through this has given me some problems. Here is what I have so far - If you could give me a pointer or 2 that would be much appreciated.
<?php
require_once("../tools/simple_html_dom.php");
require_once("../tools/Utilities.php");
$url = "http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos";
$espnHTML = file_get_html("http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos");
foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
{
foreach($rosterRow->find("td") as $playerInfo)
{
echo $playerInfo->plaintext."<br>";
}
}
?>
How can I assign these td tags into appropriate variables without "ids"? Attached is a sample screenshot that may help you understand what I am talking about.
If the columns are in the same order for every player, using your $rosterrow->find("td") should return an indexed array that you can access using $playerrow[0..n].
Then, by analyzing what corresponds to what you can make a function like this:
$players = array();
foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
{
$playerRow = $rosterRow->find("td");
$name = $playerRow[0];
$jersey = $playerRow[1];
// more can be added, of course.
$players[$name] = array();
$players[$name]["jersey"] = $jersey;
// and others
}
For table
John Appleseed | 12
---------------|----
Richard Brooks | 34
this will result in an array like
{ "John Appleseed" => { "jersey" => 12 }, "Richard Brooks" => { "jersey" => 34}}
Please let me know if this helped.
If you're open to a different approach that may be more scalable/robust, then you may also want to take a look at Kimono Labs. You can use it to create structured API based on ESPN's data. I think you'd be able to define which part of the table held names, scores, etc. and would easily be able to call the API for the desired info.

String from an array from an array from the database

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.

Splitting an external array to give different titles

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/

Is this the right way to use Sphinx from PHP?

I am just starting with Sphinx. So far I got it installed successfully, got a table called profiles on my MySQL database indexed and am able to get the correct results back using the PHP API. I am using CodeIgniter so I wrapped the default PHP API as a CodeIgniter library.
Anyway this is how my code looks like:
$query = $_GET['q'];
$this->load->library('sphinxclient');
$this->sphinxclient->setMatchMode(SPH_MATCH_ANY);
$result = $this->sphinxclient->query($query);
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
The array $to_fetch contains the ids of the matched table rows. Now I can use a typical MySQL query to get all the relevant users to display on the search page like so:
$query = 'SELECT * FROM profiles WHERE id IN('. join(',', $to_fetch) . ')';
My question are:
is this the right way to go about it? or is there a default "Sphinx way of doing it" that would be better for performance .
secondly, all I get back at the moment is the id of the matched table rows. I also want the part of the text in the column that matched. For example if a someone searches for the keyword dog and a user on the profiles table had in their about column the following text:
I like dogs. I also like ice cream.
I would like Sphinx to return:
I like <strong>dogs</strong>. I also like ice cream.
How can I do that? I tried to play around with the buildExcerpts() function but can't get it to work.
EDIT
This is how I am getting excerpts now:
// get matched user ids
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
// get user details of matched ids
$members = $this->search_m->get_users_by_id($to_fetch);
// build excerpts
$excerpts = array();
foreach($members as $member) {
$fields = array(
$member['about'],
$member['likes'],
$member['dislikes'],
$member['occupation']
);
$options = array(
'before_match' => '<strong class="match">',
'after_match' => '</strong>',
'chunk_separator' => ' ... ',
'limit' => 60,
'around' => 3,
);
$excerpt_result = $this->sphinxclient->BuildExcerpts($fields, 'profiles', $query, $options);
$excerpts[$member['user_id']] = $excerpt_result;
}
$excerpts_to_return = array();
foreach($excerpts as $key => $excerpt) {
foreach($excerpt as $v) {
if(strpos($v, '<strong class="match">') !== false) {
$excerpts_to_return[$key] = $v;
}
}
}
As you can see I am searching each query across 4 different mysql columns:
about
likes
dislikes
occupation
Because of this I don't know which of the 4 columns contains the matched keyword. It could be any of them or even more than one. So I have no choice but to run the contents of all 4 columns through the BuildExcerpts() function.
Even then I don't know which one the BuildExcerpts() returned with the <strong class="match"> tags. So I run a stpos check on all values returned by BuildExcerpts() to finally get the proper excerpt and map it to the user whose profile it belongs to.
Do you see a better way than this given my situation where I need to match against the contents of 4 different columns?
Yes that looks good way. One thing to remember the rows coming back from Mysql probably won't be in the order from sphinx.
See the FAQ on sphinx site for how to use FIELD() but personally I like to put the rows from sphinx into associative array, then just loop though the sphinx I'd list and get the row from the array. Avoids a sorting phase altogether at the expense of memory!
As for highlighting, yes do persevere with buildExcerpts - that's is the way to do it.
edit to add, this demo
http://nearby.org.uk/sphinx/search-example5-withcomments.phps
demonstrates both getting rows from mysql and "sorting" in the app. And buildExcerpts.

Displaying a JSON array in PHP (from freebase)

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
}

Categories