JSON decode any value - $var1 = $data['val1']['anyvalue']['val2']; - php

I am pulling in JSON data for a mySQL import and in setting the variables after my JSON decode statements of my JSON file I am struggling with something. My variable setting looks like so
$name = $data['available_channels']['3']['name'];
and the relevant JSON like this
"available_channels": {
"3": {
"num": 152,
"name": "Sky Sports 3",
"stream_type": "live",
"type_name": "Live Streams",
"stream_id": "3",
"stream_icon": "http://www.tv-logo.com/pt-data/uploads/images/logo/sky_uk_sports3.jpg",
"epg_channel_id": "Sky Sports 3",
"added": "0",
"category_name": "Sports UK",
"category_id": "5",
"series_no": null,
"live": "1",
"container_extension": null,
"custom_sid": ":0:86:EEE:7F2:2:11A0000:0:0:0:",
"tv_archive": 0,
"direct_source": "",
"tv_archive_duration": 0
},
My problem is that each channel for the service begins with a new number. So i need my variables to be pulled in like so,
$name = $data['available_channels']['ANY VALUE HERE']['name'];
any thoughts? I know it must be simple and I am having a blonde moment here
Thanks
UPDATE 1
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the values and asign variables
$name = $data['available_channels']['3']['name'];
UPDATE 2
Full Code Now
$data = json_decode($jsonFile, true);
for($i = 0; $i <= count($data['available_channels']); $i++){
$name = $data['available_channels'][$i]['name'];
$num = $data['available_channels'][$i]['num'];
$epg_channel_id = $data['available_channels'][$i]['epg_channel_id'];
$category_name = $data['available_channels'][$i]['category_name'];
$stream_icon = $data['available_channels'][$i]['stream_icon'];
//insert into mysql table
$sql = "INSERT INTO channels(name, num, epg_channel_id, category_name, stream_icon)
VALUES('$name', '$num', '$epg_channel_id', '$category_name', '$stream_icon')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
}
Gets about 117 of 234 rows in but the other rows are blank... any thoughts

$name = array_values($data['available_channels'])[0]['name'];
array_values returns a new array consisting of the values of the source array, renumbered from 0.

You can count the number of channels inside the array, then loop through each channel.
for($i = 0; $i <= count($data['available_channels']); $i++) {
$name = $data['available_channels'][$i]['name'];
// TODO: Do something with the name
}
Or you could do what #cske said:
$channels = [];
foreach($data['available_channels'] as $k => $v) {
// this will keep the key's the same
$channels[$k] = $v['name'];
}
Or you could choose a more OO styled approach, see it working at 3v4l:
class Channel {
private $_data;
public function __construct($json) {
$this->_data = json_decode($json, true);
}
public function parse() {
$parsed = [];
foreach($this->_data['available_channels'] as $k => $v) {
$parsed[$k] = $v['name'];
}
$this->_data['available_channels'] = $parsed;
return $this;
}
public function getByKey($key) {
return $this->_data['available_channels'][$key];
}
}
$c = new Channel($json_response);
echo 'Name for Channel 3 is: ' . $c->parse()->getByKey('3');

So after update 2, this will work
foreach($data['available_channels'] as $d) {
$name = $d['name'];
$num = $d['num'];
$epg_channel_id = $d['epg_channel_id'];
$category_name = $d['category_name'];
$stream_icon = $d['stream_icon'];
//insert into mysql table
$sql = "INSERT INTO channels(name, num, epg_channel_id, category_name, stream_icon)
VALUES('$name', '$num', '$epg_channel_id', '$category_name', '$stream_icon')";
if (!mysql_query($sql, $con)) {
die('Error : ' . mysql_error());
}
}
Or if with for loop #KDOT answer, but corrected by #Niet the Dark Absol code
$data['available_channels'] = array_values($data['available_channels']);
for($i = 0; $i <= count($data['available_channels']); $i++) {
$name = $data['available_channels'][$i]['name'];
...
}
That is simply not true if a php array has count()=5 then it's keys are 0,1,2,3,4 what couses missing rows with KDOT's answer

Related

Creating Multiple JSON Object Elements Programmatically using PHP

I need to create a JSON object, in PHP, with the following form
{
"Routes": [{
"route_ID": "49",
"geom": [{
"lat": "-30.63607",
"lng": "147.499935"
}, {
"lat": "-30.63631",
"lng": "147.499868"
}]
},
{
"route_ID": "50",
"geom": [{
"lat": "-30.63607",
"lng": "147.499935"
}, {
"lat": "-30.63631",
"lng": "147.499868"
}]
}
]
}
The problem with my code is that I can't seem to find a way of concatenating the JSON elements from the $jsonString, The code as it is just produces "route_ID": "50".
(Yes I agree there are a great many questions on stackoverflow on this question, but they just about all refer to single elements derived from a static array). By the way, I am given the $jsonString and need to preprocess it in the code below.
$jsonString = "[{\"route_ID\":\"49\",\"geom\":\"<LineString><coordinates>147.499935,-30.63607 <\\/coordinates><\\/LineString>\"},{\"route_ID\":\"50\",\"geom\":\"<LineString><coordinates>147.499935,-30.63607<\\/coordinates><\\/LineString>\"}]";
/* PHP Code */
$jsonArray = json_decode($jsonString, true);
$json = new stdClass();
$json_Routes = new stdClass();
$route_geom_Array = array();
foreach ($jsonArray as $record) {
print_r($record);
$geomString = $record["geom"];
$geomString = str_replace('<LineString><coordinates>', ' ', $geomString);
$geomString = str_replace('</coordinates></LineString>', ' ', $geomString);
$geomString = trim($geomString);
$route_geom_Array = explode(' ', $geomString);
for ($i = 0; $i < sizeof($route_geom_Array); $i++) {
$var = explode(',', $route_geom_Array[$i]);
$route_geom[] = array('lat' => $var[1], 'lng' => $var[0]); // lat long
}
$json->route_ID = $record["route_ID"]; //<- Problem area
$json->geom = $route_geom; //<- Problem area
}
$json_Routes->Routes = $json;
$jsonArray = json_encode($json_Routes);
echo $jsonArray;
exit ();`
Can someone give me a clue on how do this.
Thanks
You need to make $json_Routes->Routes an array and push the $json structures within the foreach block, e.g.:
$json_Routes->Routes = [];
foreach ($jsonArray as $record) {
// Existing code ...
$json_Routes->Routes[] = $json;
}
You need to push objects to array, here solution :
$jsonArray = json_decode($jsonString, true);
$json_Routes = new stdClass();
$route_Array = [];
$route_geom_Array = [];
$route_ID_Array = [];
$items = [];
$index = 0;
foreach ($jsonArray as $record) {
//print_r($record);
$geomString = $record["geom"];
$geomString = str_replace('<LineString><coordinates>', ' ', $geomString);
$geomString = str_replace('</coordinates></LineString>', ' ', $geomString);
$geomString = trim($geomString);
$route_geom_Array = explode(' ', $geomString);
for ($i = 0; $i < sizeof($route_geom_Array); $i++) {
$var = explode(',', $route_geom_Array[$i]);
$route_geom[] = array('lat' => $var[1], 'lng' => $var[0]); // lat long
}
$json = new stdClass();
$json->route_ID = $record["route_ID"]; //<- Problem area
$json->geom = $route_geom; //<- Problem area
array_push($route_Array,$json);
}
$json_Routes->Routes = $route_Array;
$result = json_encode($json_Routes);
echo $result;
exit();

Convert JSON from MySQL to PHP

So i have this JSON in my MySQL Database
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
Now i want to work with this data in PHP.
I got the JSON by doing this in PHP:
$sql = "SELECT article FROM test WHERE id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$aricle = $row["article"];
} else {
echo "Something went wrong";
}
After that i did this which resulted in getting a JSON Array:
$tarray = json_decode($article, TRUE);
What can i do now to get the values from the JSON?
For example i want the value of the price in a variable called $price.
$price = $tarray[11011001]['price'];
Or you can loop through the results if you have many articles
$tarray = json_decode($json,true);
foreach ($tarray as $index => $item)
{
$price[] = $item['price'];
}
var_dump($price);
Assuming you might have a collection of items, you can map the ids to prices with array_column.
<?php
$json =<<<JSON
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
JSON;
$items = json_decode($json, TRUE);
$ids_prices = array_column($items, 'price', 'id');
var_export($ids_prices);
Output:
array (
11011001 => 4,
)
Only one item, but you don't know the key up front?
if(count($items) === 1) {
$item = array_pop($items);
$price = $item['price'];
}
echo $price;
Output:
4
First you have a sql injection, you must create a prepared query if you have data from users.
$sql = "SELECT article FROM test WHERE id = :id";
$query = $con->prepare($sql);
$query->bindValue(":id", $id);
$query->execute();
$result = $query->fetch();
if ($result) {
// $article will be stdClass if json correct
$article = json_decode($result['article']);
$price = $article->price;
// or $article = json_decode($result['article'], true);
// $price = $article['price'];
}
Just an example

How to get data from multi dimensional array

( Full pastebin: https://pastebin.com/C4qV5YYv)
I'm trying to select data from a (long) multi dimensional array, but with all things I tried the page just showed as blank. I'm trying to access the data with the name instead of it's rank in the list.
{
"playerstats": {
"steamID": "76561198035223060",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 38694
},
{
"name": "total_deaths",
"value": 33362
},
{
"name": "total_time_played",
"value": 2148546
},
{
"name": "total_planted_bombs",
"value": 770
},
{
"name": "total_defused_bombs",
"value": 271
},
{
"name": "total_wins",
"value": 12394
}, So on and so on......
I'm currently using this to get data from the array: $kills = $jsonforgame['playerstats']['stats'][0]['value'];
This works when you only need a couple of values, but it gets really tidy when I need to select values further down, like; $hit = $jsonforgame['playerstats']['stats'][47]['value'];
Is there anyway for me to select the stats with the name, like this: $hit = $jsonforgame['playerstats']['stats']['total_shots_fired']['value']; instead of the number.
Thanks in advance.
You may go for something like this:
function getStat($data, $name)
{
return array_filter($data, function($item) use ($name) {
return $item && $item['name'] === $name;
})[0]['value'];
}
$hit = getStat($jsonforgame['playerstats']['stats'], 'total_shots_fired');
But the more efficient way would be to change your stats api so it serves key-value pairs, if it is possible, ofc.
One way would be to change how you create the array as so:
{
"playerstats": {
"steamID": "76561198035223060",
"gameName": "ValveTestApp260",
"stats":
{
"total_kills": 38694,
"total_deaths": 33362,
"total_time_played": 2148546,
...
}
then simply access by $kills = $jsonforgame['playerstats']['stats']['total_kills']
In case you can't change the array, you could also try
$specs = array("total_kills", "total_deaths", "total_time_played"); // and so on
foreach ( $specs as $spec )
$$spec = $jsonforgame['playerstats']['stats'][ $spec ]['value'];
After that you can use each spec by name, for example $total_kills
If you want to use shorter variable names you can change the code like this
$specs = array(
"kills" => "total_kills",
"died" => "total_deaths",
"played" => "total_time_played"
); // and so on
foreach ( $specs as $key => $spec )
$$key = $jsonforgame['playerstats']['stats'][ $spec ]['value'];
echo $kills; // output $jsonforgame['playerstats']['stats']['total_kills']['value']
Another approach
$count = count($jsonforgame['playerstats']['stats']);
for ( $i = 0; $i < $count; $i++ ) {
$name = $jsonforgame['playerstats']['stats'][ $i ]['name'];
$value = $jsonforgame['playerstats']['stats'][ $i ]['value'];
$$name = $value;
}
and with use of the array with shorter variable names
$specs = array(
"total_kills" => "kills",
"total_deaths" => "died",
"total_time_played" => "played",
); // and so on
$count = count($jsonforgame['playerstats']['stats']);
for ( $i = 0; $i < $count; $i++ ) {
$name = $specs[ $jsonforgame['playerstats']['stats'][ $i ]['name'] ];
$value = $jsonforgame['playerstats']['stats'][ $i ]['value'];
$$name = $value;
}

PHP Push into an array

I have a PHP loop that's getting data from my table and pushing it into an array.
$children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c");
$temp = array();
while ($child = mysql_fetch_assoc($children)) {
// Get the child's reatings
$ratings = mysql_query('
SELECT r.behaviourID, t.points, t.typeName
FROM behaviourRatings as r
JOIN behaviourTypes as t
ON r.behaviourID = t.typeID
WHERE r.childID = ' . $child['id']);
// Loop over the ratings
$totalPoints = 0;
while ($childRatings = mysql_fetch_array($ratings)){
$totalPoints = ($totalPoints + $childRatings['points']);
}
// We can only max out at our set max
if(($totalPoints + $maxPoints) > $maxPoints) {
$total = $maxPoints;
} else if($totalPoints < 0){
$total = ($maxPoints + $totalPoints);
}else{
$total = ($maxPoints - $totalPoints);
}
// Set the child array
$temp[] = $child;
}
$response = array();
$response['timestamp'] = $currentmodif;
$response['children'] = $temp;
echo json_encode($response, JSON_PRETTY_PRINT);
I want to add another key/value to the array called points and assign its value as $total.
I tried doing $temp['points'] = $total but that put it outside of the array and not with the outer loops data.
This is the result of the function:
{
"timestamp": 1482918104,
"children": [
{
"id": "1",
"name": "Maya",
"age": "5",
"photoName": "maya.png",
"panelColor": ""
},
{
"id": "2",
"name": "Brynlee",
"age": "3",
"photoName": "brynlee.png",
"panelColor": "green"
}
]
}
I want to show the points for each of those children but I am unsure how to add it to that part of the array.
You should add it to the $child variable, just before adding that variable to the $temp array:
$child['points'] = $total;
$temp[] = $child;
Also you can reduce requests to database by getting all child's ratings in one query.
Something like this:
$children = mysql_query("SELECT c.id, c.name, c.age, c.photoName, c.panelColor FROM children as c");
$childrenIds = [];
while ($child = mysql_fetch_assoc($children)) {
$childrenIds[] = $child['id'];
}
if (!empty($childrenIds)) {
$ratings = mysql_query('
SELECT r.behaviourID, t.points, t.typeName
FROM behaviourRatings as r
JOIN behaviourTypes as t
ON r.behaviourID = t.typeID
WHERE r.childID IN (' . implode(',', $childrenIds) . ')');
}

mongodb in php-insert array to mongo db collection

i use mongodb in php and have a problem to insert $subitems array to mongodb collection.
php code:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$errors = array();
$alarm = array();
$item_name = data::test_input($_POST["item_name"]);
$folder_name = data::test_input($_POST["folder_name"]);
$subitem_num = data::test_input($_POST["subitem_num"]);
for($i=1;$i<=$subitem_num;$i++){
${"subitem_name$i"} = data::test_input($_POST["subitem_name".$i]);
${"subitem_file$i"} = data::test_input($_POST["subitem_file".$i]);
if(count($errors)==0){
$subitems = array(${"subitem_name$i"}=>${"subitem_file$i"});
}
}
if(empty($item_name)){
$errors['item_name']= "insert item";
}
if(empty($folder_name)){
$errors['folder_name']= "insert folder";
}
if(count($errors)==0){
$query = array(
"item_name" => $item_name,
"status" => 0,
"folder_name" => $folder_name,
"subitem" => $subitems
);
$result = items::insert($query);
if($result) $alarm['success_additem'] = "submit done";
}
}
i want record values to mongodb collection like this:
{ "_id" : ObjectId("542e71b333e916542a00002e"), "item_name" : "users management", "status" :0, "folder_name" : "users", "subitem" : { "a" : "a.php","b" : "b.php" },"c" : "c.php" }
how to write php code for insert to mongodb collection?
I assume your problem is that the subitem field in your document never contains more than a single key/value pair when inserted into the database.
for($i=1;$i<=$subitem_num;$i++){
${"subitem_name$i"} = data::test_input($_POST["subitem_name".$i]);
${"subitem_file$i"} = data::test_input($_POST["subitem_file".$i]);
if(count($errors)==0){
$subitems = array(${"subitem_name$i"}=>${"subitem_file$i"});
}
}
Based on that for loop, you're over-writing $subitems in each iteration. I assume you mean to assign a key within it, in which case you'd be better served with the following:
$subitems = array();
for($i = 1; $i <= $subitem_num; $i++) {
$key = data::test_input($_POST["subitem_name".$i]);
$value = data::test_input($_POST["subitem_file".$i]);
if (count($errors) == 0) {
$subitems[$key] = $value;
}
}
For the record, I have no idea why you're checking $errors here, as it's assigned once at the top of this function and doesn't appear to be modified within the for loop; however, I left it in place so it lines up with the original example you've provided.
Also, there is really no reason to use dynamically-named variables here. Fixed terms such as $key and $value make the code much more readable.

Categories