Complex JSON array to MySQL via PHP - php

I'm aiming to put a selection of info from a JSON result into MySQL via PHP. The specific issue I'm having is with accessing specific info from the JSON result, as it isn't a simple list format. Here is a screenshot of the kind of structure I'm talking about with the information I'm interested in highlighted.:
I sadly don't have enough reputation to post an image so here it is rehosted on imgur:
Under ['streams'] will be a list of 100 streams. From each of those results I want to take the highlighted information and place it into a MySQL table.
I'm fairly comfortable with simpler JSON files and easier applications of json_decode
$result = json_decode($json);
foreach ($result as $key => $value)
I'm thinking perhaps I need to use the depth variable? But finding it difficult to find much information on it.
If anyone can give me any help or point me towards a good source of info (As I have struggled to find anything) then it would be much appreciated.
If anymore information would be useful let me know and I will add it.
edit: link to json request: https://api.twitch.tv/kraken/streams?limit=2/
<?php
//import data from twitch
$json = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams?limit=100/"), true);
//create a DB connection
$con = mysql_connect("CONNECTION INFO :D");
mysql_connect_db('NOPE', $con);
$result = json_decode($json);
foreach ($result as $key => $value) {
if ($value) {
mmysql_query("INSERT INTO twitchinfo (viewers, status, display_name, game, delay, name) VALUES ($value->viewers, $value->status,$value->display_name,$value->game,$value->delay,$value->name)")or die(mysql_error());
}
// end connection
mysql_close($con);
}
?>

Your JSON object is basically something like...
[
links: {
self: http://example.com,
next: http://example.com/foo,
},
streams: [
{
channel: {
foo: 'bar'
},
one: 'one',
somethingElse: 'Something else',
moreStuff: 'more stuff',
}
]
]
When you decode a JSON object you are left with a PHP Object/Array that represents the object.
$x = json_decode('[1,2,3]')
is going to give you the same array as...
$x= array(1,2,3)
If you load up the JSON you've shown and run this:
foreach ($result as $key => $value)
This is the same as accessing $result->links and $result->streams. Each contains more data.
If I wanted to grab the 'foo' element from the channel in my example I would do:
$streams = $result->streams //Get the streams array
$stream = $streams[0] //Get the first stream object
$channel = $stream->channel //Get the channel object
$foo = $channel->foo //Get the value 'bar' out of the foo property.
As long as the structure is predictable (and it is), I can iterate over the streams since it's just an array.
$streams = $result->streams //Get the streams array
foreach ($streams as $stream) {
$channel = $stream->channel //Get the channel object
$foo = $channel->foo //Get the value 'bar' out of the foo property of every stream.
}

Opening this url in browser -
https://api.twitch.tv/kraken/streams?limit=100/
Gives me a JSON. I copied it in -
http://www.jsoneditoronline.org/
and saw that it has streams and _links keys.
As per your issue is concerned, try this -
$result = json_decode($json);
if( isset( $result['streams'] )){
$streams = $result['streams'];
foreach($streams as $stream) {
$viewers = $stream->viewers;
$status = $stream->channel->status;
$display_name = $stream->channel->display_name;
$game = $stream->channel->game;
$delay = $stream->channel->delay;
$name = $stream->channel->name;
$sql = "INSERT INTO twitchinfo (viewers, status, display_name, game, delay, name) VALUES ($viewers, \"$status\", \"$display_name\", \"$game\", $delay, \"$name\")";
mysql_query($sql)or die(mysql_error());
}
}

May be you can do this:
$values = array();
$result = json_decode($json);
foreach($result['streams'] as $stream) {
array_push(
$values,
array(
'viewers' => $stream['viewers'],
'status' => $stream['channel']['status'],
'display_name' => $stream['channel']['display_name'],
'game' => $stream['channel']['game'],
'delay' => $stream['channel']['delay'],
'name' => $stream['channel']['name'],
)
);
}
Or:
foreach($result['streams'] as $stream) {
$sqlQuery= "INSERT INTO TABLE(viewers, status, display_name, game, delay, name) VALUES ($stream['viewers'], $stream['channel']['status'], $stream['channel']['display_name'], $stream['channel']['game'], $stream['channel']['delay'], $stream['channel']['name']);"
//dbHandler->executeQuery($sqlQuery);
}

Related

PHP/MYSQL: Access data in Array of Dictionaries

I receive a JSON stream from an iphone that contains some simple strings and numbers as well as an array of dictionaries. I would like to work with these dictionaries, in essence, storing the data in each of them in a separate MYSQL record.
To get access to the strings as well as the array from the JSON stream, I am using the following:
$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);
$authString = jsonArray['authstring'];
$itemsArray = $jsonArray['itemsArray'];
This is what itemsArray looks like before being sent to the server:
itemsArray = (
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 6;
iid = 0;
title = "test";
complete = 1;
userid = 99;
whenaddedstr = "2018-06-21 14:10:23";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 37;
iid = 0;
title = "how about this";
userid = 88;
whenaddedstr = "2018-07-07 16:58:31";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 38;
iid = 0;
title = reggiano;
userid = 1;
whenaddedstr = "2018-07-07 17:28:55";
}
etc.
I guess I should probably put these dictionaries into an Associative Array in order to save them.
I am struggling, however, with how to reference and get the objects. From what I can tell the following code is returning empty values in so far as $message comes back as empty.
$anitem = $jsonArray['itemsArray'][0];
$message=$anitem;
$title = $jsonArray['itemsArray'][0].[item];
$message.=$title;
Can anyone suggest proper syntax to grab these items and their properties?
Thanks in advance for any suggestions.
I find it strange that people associate things with a dictionary, while it is nothing more then a multidimensional array.
If you can read JSON, you see that the variable will have an index containing each entry.
For PHP:
foreach($jsonArray as $array){
// note that $array is still an array:
foreach($array as $v){
echo "Hurray!: '$v'";
}
}
If it really was an object (or cast to an object), the only thing you need to change is how you access the variable (as in any other language). In PHP it would be:
echo $jsonArray[0]->lasttouchedstr;
Or of it was the same loop:
foreach($jsonArray as $v){
echo $v->lasttouchedstr;
}
Multidimensional?
echo $jsonArray['itemsArray'][0][item]; // array
echo $jsonArray->itemsArray[0][item]; // if items array is an actual array and jsonArray an object.
Most languages associate things written as a . that the left side is an object. In PHP it's written as ->.

Need to create Json object in php

I want to create a json object using php like below as I need to create a stacked bar chart using d3.js, hence I am using data from oracle table and need the json data as above image.
My table has these 3 columns. (ID, NAME, Layers) like:-
ID, NAME, Layers
1 ABC a:8,b:10
2 WWW c:8,d:7
When I am fetching data from oracle, my php code is:-
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
$streamArr[] = $row;
}
header("Access-Control-Allow-Origin: *");
echo json_encode($streamArr);
I am getting this error:-
Warning: [json] (php_json_encode) type is unsupported, encoded as null in line 48
json output as:-
[["1","ABC",{"descriptor":null}],["2","WWW",{"descriptor":null}]]
can you please help me in rectifying with this issue?
The error message refers to a field you didn't mention in the example. Maybe just don't select unneeded fields?
If you fix that, you still won't get the desired JSON structure. To get layers as an object in every element of data in the resulting JSON, you need to convert the string values stored in the database to PHP arrays before encoding.
You could do that with similar code:
while (($row = oci_fetch_array($stid, OCI_ASSOC)))
{
$row['layers'] = array_map(function($el) {
return explode(':', $el);
}, explode(',', $row['layers']));
$streamArr[] = $row;
}
#marekful answer is really nice, not easiest to understand but efficient and short!
Here you have a longer and not so efficient, but maybe easier to get.
$streamArr = array();
while (($row = oci_fetch_array($stid, OCI_ASSOC)))
{
// Get ID and NAME
$data = array(
'id' => $row['ID'],
'name' => $row['NAME'],
'layers' => array()
);
// Get Layers by split by comma
$layers = explode(',', $row['layers']);
foreach ($layers as $layer) {
// Get layer parts by slit with double-point
$layersPart = explode(':', $layer);
foreach ($layersPart as $key => $value) {
$data['layers'][$key] = $value;
}
}
// Add to global array
$streamArr[] = $data;
}
echo json_encode($streamArr);

Trying to get correct/exact string from json

I am trying to get string from JSON, that i should use later. The problem is that my code (depending which file i use) doesn't give me my string with special characters. Strange thing is that one file does everything right, while other is not, even through they contain exactly the same PHP code.
This is that i get from the first one:
[title] => 1611 Plikiškiai–Kriukai (Incorrect)
And from another:
[title] => 1611 Plikiškiai–Kriukai (Correct one)
Here is some code:
function get_info($id) {
$json = file_get_contents('http://restrictions.eismoinfo.lt/');
$array = json_decode($json, true);
//get object/element with such id, so then it would be possible take needed parts/values
$result_array = array();
foreach ($array as $key => $value) {
if ($id == $value['_id']){
$result_array = $value;
}
}
//Street name
$title = $result_array['location']['street'];
echo $title;
}
get_info($id); //$id is some string like 143crt9tDgh5
1st file is located in folder "test", while 2nd in "project".
Any ideas why is that happening?

str_replace (search) large number of strings from a certain JSON value?

What is the best and fastest approach to do a string search and replace from a certain JSON value if it has lets say more than 100 strings to search in and each string needs its own unique replacement?
Is it better to create a php subclass with preg_replace using arrays and then import this into another PHP file where the JSON gets parsed?
My PHP knowledge is not that great and would appriciate if someone can guide me through this with some examples.
Here is my JSON code:
<?php
header('Content-Type: application/json');
$licensePlate = $_GET['kenteken'];
$json = file_get_contents('https://opendata.rdw.nl/resource/m9d7-ebf2.json?$q='.$licensePlate.'');
$array = json_decode($json);
if(count($array,1)==0) {
$data = ['resource' => ['code' => '404']];
echo json_encode($data);
return;
}
$item = array();
foreach ($array as $value) {
$item['code'] = '200';
$item['Aantalcilinders']=$value->aantal_cilinders;
$item['Aantalzitplaatsen']=$value->aantal_zitplaatsen;
$item['BPM']=$value->bruto_bpm;
$item['Cilinderinhoud']=$value->cilinderinhoud;
$item['Datumaanvangtenaamstelling']=$value->datum_tenaamstelling;
$item['DatumeersteafgifteNederland']=$value->datum_eerste_afgifte_nederland;
$item['Datumeerstetoelating']=$value->datum_eerste_toelating;
$item['Eerstekleur']=$value->eerste_kleur;
$item['Handelsbenaming']=$value->handelsbenaming; <--this value needs to be replaced in some cases
$item['Inrichting']=$value->inrichting;
$item['Kenteken']=$value->kenteken;
$item['Merk']=$value->merk;
}
$data = ['resource' => ($item)];
echo json_encode($data);
?>
Thanks!
Ps. Excuse my language, I'm from the Netherlands.

PHP: (PDO) Mysql most effective way to add sting to returned value out of db

In a mysql database I store some image names without the exact path.
So what I like to do is add the path before I load the returned array into jQuery (json) to use it in the JQ Galleria plugin.
In the columns I've got names likes this:
11101x1xTN.png 11101x2xTN.png 11101x3xTN.png
Which in the end should be like:
./test/img/cars/bmw/11101/11101x1xTN.png
./test/img/cars/bmw/11101/11101x2xTN.png
I could just add the whole path into the database but that seems 1. a wast of db space. 2. Then I need to update he whole db if the images path changes.
I could edit the jQuery plugin but it doesn't seem practical to update the source code of it.
What is the right thing to do and the fasted for processing?
Can you add a string after you make a db query and before you fetch the results?
part of the function where I make the query:
$needs = "thumb, image, big, title, description";
$result = $get_queries->getImagesById($id, $needs);
$sth=$this->_dbh->prepare("SELECT $needs FROM images WHERE id = :stockId");
$sth->bindParam(":stockId", $id);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
this is the foreach loop:
$addurl = array('thumb', 'image', 'big');
foreach ($result as $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
}
}
}
the array looks like this:
Array
(
[0] => Array
(
[thumb] => 11101x1xTN.png
[image] => 11101x1xI.png
[big] => 11101x1xB.png
[title] => Title
[description] => This a blub.
)
)
The url should be add to thumb, image and big.
I tried to change the array values using a foreach loop but that didn't work. Also not noting if the use of that would course a unnecessary slowdown.
well, you almost nailed it. only thing you forgot is to store your $val back in array.
foreach ($result as $i => $array) {
foreach ($array as $item => $val) {
if (in_array($item, $addurl)){
$val = '/test/img/cars/bmw/11101/'.$val;
$result[$i][$item] = $val;
}
}
}
however, I'd make it little shorter
foreach ($result as $i => $array) {
foreach ($addurl as $item) {
$result[$i][$item] = '/test/img/cars/bmw/11101/'.$array[$item];
}
}
}
Assuming your array looks like this:
$result = array("11101x1xTN.png", "11101x2xTN.png", "11101x3xTN.png");
A simple array_map() can be used.
$result_parsed = array_map(function($str) { return './test/img/cars/bmw/11101/'.$str; }, $result);
As seen Here

Categories