Format JSON with PHP - php

I need some helping formatting my JSON correctly. Create parent objects for each of the activities and then add children to them. With the example data below it would be one parent activity for 'Test' with two children and another parent for 'Test2' with three children. I've linked in two jsonblobs with the format i'm getting and the format I need. Any help would be appreciated.
+---------------+-------+--------------+------------+------------+--------+
| ACTIVITY_NAME | GROUP | START_DATE | END_DATE | COMPLETED | TOTAL |
+---------------+-------+--------------+------------+------------+--------+
| Test | 1 | 04/30/2015 | 05/01/2015| 10 | 15 |
| Test | 2 | 04/30/2015 | 05/01/2015| 20 | 25 |
| Test2 | 1 | 05/2/2015 | 05/03/2015| 30 | 35 |
| Test2 | 2 | 05/2/2015 | 05/03/2015| 40 | 45 |
| Test2 | 3 | 05/2/2015 | 05/03/2015| 50 | 55 |
+---------------+-------+--------------+------------+------------+--------+
PHP:
<?php
include("connect.php");
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "<query>";
$stmt = sqlsrv_query( $conn, $sql);
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
foreach ($json as $result) {
$data[data][][$result['ACTIVITY_NAME']]['children'] = $result;
}
echo json_encode($data);
?>
This is what i'm getting: https://jsonblob.com/5550c921e4b002ae4e370469
This is what I need: https://jsonblob.com/5550c942e4b002ae4e370471
Edit -
Here is what my working script ended up looking like:
<?php
include("connect.php");
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "<query> ";
$stmt = sqlsrv_query($conn, $sql);
// This is where the data will be organized.
// It's better to always initialize the array variables before putting data in them
$data = array();
// Get the rows one by one
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// Extract the activity name; we want to group the rows by it
$name = $row['ACTIVITY_NAME'];
$group = '';
$sdate = '';
$edate = '';
$completed = '';
$total = '';
$perc = '';
// Check if this activity was encountered before
if (! isset($data[$name])) {
// No, this is the first time; we will make room for it, first
$data[$name] = array(
// Remember the name
'ACTIVITY_NAME' => $name,
'MAINTENANCE_GROUP' => $group,
'START_DATE' => $sdate,
'END_DATE' => $edate,
'COMPLETED' => $completed,
'TOTAL_CLUSTERS' => $total,
'COMPLETE_PERC' => $perc,
// No children yet
'children' => array(),
);
}
// Put the row into the list of children for this activity
$data[$name]['children'][] = $row;
}
// Here, the entries in $data are indexed by the values they also have in 'ACTIVITY_NAME'
// If you want them numerically indexed, all you have to do is:
$data = array_values($data);
echo json_encode(array('data' => $data));
//echo json_encode($data);
?>

You didn't show the query/queries you run but for such a simple task I think a single query is enough. The outer do/while loop on sqlsrv_next_result() is not needed. You have to use it when you send more than one query (separated by semicolons) in a single call to sqlsrv_query().
You do not need to run two times through the result set. You can organize your data as soon as you get it from the database.
All you need is to check the values you get from the database and create the data structure as you need:
// ...
$stmt = sqlsrv_query($conn, $sql);
// This is where the data will be organized.
// It's better to always initialize the array variables before putting data in them
$data = array();
// Get the rows one by one
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// Extract the activity name; we want to group the rows by it
$name = $row['ACTIVITY_NAME'];
// Check if this activity was encountered before
if (! isset($data[$name])) {
// No, this is the first time; we will make room for it, first
$data[$name] = array(
// Remember the name
'ACTIVITY_NAME' => $name,
// No children yet
'children' => array(),
);
}
// Put the row into the list of children for this activity
$data[$name]['children'][] = $row;
}
// Here, the entries in $data are indexed by the values they also have in 'ACTIVITY_NAME'
// If you want them numerically indexed, all you have to do is:
$data = array_values($data);
// That's all

Change these 3 lines:
foreach ($json as $result) {
$data[data][][$result['ACTIVITY_NAME']]['children'] = $result;
}
To this:
foreach ($json as $result) {
$data['data'][] = array('ACTIVITY_NAME' => $result['ACTIVITY_NAME'], 'children' => $result);
}

You can save the children fields in an array
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$children = array("MAINTENANCE_GROUP" => $row["MAINTENANCE_GROUP"], "START_DATE" => $row["START_DATE"],
"END_DATE" => $row["END_DATE"], "COMPLETED" => $row["COMPLETED"], "TOTAL" => $row["TOTAL"] );
$json[] = array("MAINTENANCE_GROUP" => $row["MAINTENANCE_GROUP"], "children" => $children);
}
} while ( sqlsrv_next_result($stmt) );

i guess use below code
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// Extract the activity name; we want to group the rows by it
$name = $row['ACTIVITY_NAME'];
// Check if this activity was encountered before
if (! isset($data[$name])) {
// No, this is the first time; we will make room for it, first
$data[$name] = array(
// Remember the name
'ACTIVITY_NAME' => $name,
// No children yet
'children' => array(),
);
}
// Put the row into the list of children for this activity
$data[$name]['children'][] = $row;
}
$json=json_encode($data);

Related

Selecting associative array in mysql

I currently have the following:
$query='select concat("[",key,"=>",value,"]")
from table';
if(isset($query))$r=$mysql->query($query);
if(isset($r)){
for($i=1;$i<=$r->num_rows;$i++){
$r->data_seek($i-1);
$a[$i-1]=$r->fetch_array(MYSQLI_ASSOC);
$a[$i-1]=parse_array($a[$i-1]);
}
}
$mysql->close;
function parse_array($parent){
foreach($parent as$k=>$val){
if(strpos($val,']')){
$array=explode(',',substr($val,1,-1));
foreach($array as$val){
$keypair=explode("=>",$val);
$newarray[$keypair[0]]=$keypair[1];
}
$parent[$k]=parse_array($newarray);
}
}
}
There has to be a more elegant way of doing this - perhaps built into MySQL? I'm trying to minimize the time this spends running PHP - I would like it to arrive to PHP already in array form, but MySQL kicks Subquery returns more than one result if I attempt a subquery.
Edit: Here's table:
+----------+----------+
| value | key |
+----------+----------+
| img.jpg | src |
+----------+----------+
Output should be:
[
'src'=>'img.jpg'
]
Just move all of the manipulation over to php. Fetch the query with numeric indexes. Make the assumption that the every even index is a key and every odd index is a value (or vice versa).
$query = 'select key1, value1, key2, value2
from table';
if(isset($query))
$result = $mysql->query($query);
if(isset($result)) {
$newResult = []; // if your version of php doesn't support this syntax to create a new array use `$newResult = array();`
while($row=$result->fetch_array(MYSQLI_NUMERIC)) {
$newResult[] = build_assoc_array($row);
}
}
$mysql->close;
function build_assoc_array($flat_arr) {
$newArr = [];
$numCol = count($flat_arr);
for($colIndex = 0; $colIndex < $numCol; $colIndex+=2) {
$newArr[$flat_arr[$colIndex]] = $flat_arr [$colIndex+1];
}
return $newArr;
}

PHP Array select result from other array

I have a sql table with some category, i get them in a array.. all fine but when i try to get data from another table foreach category, always return me for first category selected.
This is my code:
$gameguidecategoryes = array();
$gameguides = array();
$dbselectgameguidecategoryes = new DB_MSSQL;
$dbselectgameguidecategoryes->Database=$newweb_db;
$dbselectgameguidecategoryes->query("Select GameGuideCatNr,GameGuideCatName_$languageid as GameGuideCatName,GameGuideCatImage from GameGuide_Category where GameGuideCatVisible = 1 order by GameGuideCatOrder asc");
for($i=0;$i < $dbselectgameguidecategoryes->num_rows();++$i) {
if ($dbselectgameguidecategoryes->next_record()){
$GameGuideCatNr = $dbselectgameguidecategoryes->f('GameGuideCatNr');
$GameGuideCatName = $dbselectgameguidecategoryes->f('GameGuideCatName');
$GameGuideCatImage = $dbselectgameguidecategoryes->f('GameGuideCatImage');
}
$gameguidecategoryes_temp = array(
'ggcname' => $GameGuideCatName,
'ggcimg' => $GameGuideCatImage,
);
$gameguidecategoryes[$i] = $gameguidecategoryes_temp;
$dbselectgameguide = new DB_MSSQL;
$dbselectgameguide->Database=$newweb_db;
$dbselectgameguide->query("Select GameGuideID,GameGuideName_$languageid as GameGuideName from GameGuide_Content where GameGuideCat = $GameGuideCatNr and GameGuideVisible = 1 order by GameGuideOrder asc");
for($ii=0;$ii < $dbselectgameguide->num_rows();++$ii) {
if ($dbselectgameguide->next_record()){
$GameGuideID = $dbselectgameguide->f('GameGuideID');
$GameGuideName = $dbselectgameguide->f('GameGuideName');
}
$gameguides_temp = array(
'ggid' => $GameGuideID,
'ggn' => $GameGuideName,
);
$gameguides[$ii] = $gameguides_temp;
}
}
Why $gameguides return data only from first category?
Thank you
Your second loop keeps getting trashed by the first loop. e.g. Consider what happens:
You fetch your categories, and (let's pretend) there's 4 of them.
You store some information in $gameguidecategoryes[0]
You run the second query, get some content for category #0, say, 3 records
That gets stored in $gameguides[0], [1], [2]
Your outer loop ticks again, and you start on categoryes[1]
The inner loop ticks again, you get 4 records, and now you're storing them into the SAME again: $gameguides[0], [1], [2], [3], etc...
You've now trashed the data you fetched in the first loop, and will
do so for every category you fetch.
This code is very inefficient. You should learn how to use JOINs, and fetch into a single structure, e.g.
SELECT category.id, category.name, ...., content.id, content.name
FROM categories
LEFT JOIN content ON categories.id = content.category_id
ORDER BY ...
and then something like
$data = array();
while($row = fetch row from db) {
if (!isset($data[$row['category.id']]) {
$data[$row['category.id']] = array(
'name' => $row['category.name'],
'content' => array()
);
}
$data[$row['category.id']]['content'][] = array(
... save content data here
);
};
Better work on clean code
$gameguidecategoryes = $gameguides = $gameguidescategoryids = array();
$dbselectgameguidecategoryes = new DB_MSSQL;
$dbselectgameguidecategoryes->Database=$newweb_db;
$dbselectgameguidecategoryes->query("Select GameGuideCatNr,GameGuideCatName_$languageid as GameGuideCatName,GameGuideCatImage from GameGuide_Category where GameGuideCatVisible = 1 order by GameGuideCatOrder asc");
while ($dbselectgameguidecategoryes->next_record()) {
$gameguidescategoryids[] = $dbselectgameguidecategoryes->f('GameGuideCatNr');
$gameguidecategoryes[] = array(
'ggcname' => $dbselectgameguidecategoryes->f('GameGuideCatName'),
'ggcimg' => $dbselectgameguidecategoryes->f('GameGuideCatImage'),
);
}
if (count($gameguidescategoryids)) {
$dbselectgameguide = new DB_MSSQL;
$dbselectgameguide->Database=$newweb_db;
$dbselectgameguide->query("Select GameGuideID,GameGuideName_$languageid as GameGuideName from GameGuide_Content where GameGuideCat IN (".implode(',', $gameguidescategoryids).") and GameGuideVisible = 1 order by GameGuideOrder asc");
while ($dbselectgameguide->next_record()){
$gameguides[] = array(
'ggid' => $dbselectgameguide->f('GameGuideID'),
'ggn' => $dbselectgameguide->f('GameGuideName'),
);
}
}

unexpected behavior of object pushed in an array

I've made a script which creates an object in a foreach loop, the object gets filled with information and then goes in a nested foreach loop adding even more information.
The script is to make an overview of information, posts by user + some other information
$data = array();
foreach ($users as $user)
{
$row = new stdClass();
$row->user = $user;
$row->name = fullname($user);
$posts = getPosts($user);
foreach ($posts as $post)
{
$row->title = $post->title;
$row->datetime = $post->date;
$row->views = getViews($post->id);
$data[] = $row;
}
}
When the script is done all "rows" in $data are the same per user, all showing the last added row for that user.
When I check the row before putting it in the array, it's the information I expect, it seems the object is still actively used although I've put it in an array.
Should I close the object before putting it in an array or something else?
Thanks in advance!
=EDIT=
$data[] = $row; is in the right spot because I want the output to be like this:
Emma | 'My first post!' | 22-10-2014 | 8
Emma | 'posting again!' | 23-10-2014 | 24
Emma | 'Back from ...' | 02-01-2014 | 69
Rick | 'youknowit' | 10-10-2013 | 45
Freud | 'Yo momma' | 01-01-1970 | 123
Frued | 'fruitsalad' | 02-02-2010 | 3
[Update] Your code makes a lot more sense with the new information added to the question :) And the solution gets far more easy : Simply clone $row in each $post-loop .
foreach ($users as $user)
{
$row = new stdClass();
$row->user = $user;
$row->name = fullname($user);
$posts = getPosts($user);
foreach ($posts as $post)
{
$item = clone $row; //<-- clone $row, $data will end up as you desire
$item->title = $post->title;
$item->datetime = $post->date;
$item->views = getViews($post->id);
$data[] = $item;
}
}

How can I loop through an array while averaging the values of one element and only keep the newly averaged field in PHP?

I have database that contains scores which are stored daily. I want to average each months scores for each user. So far I have this:
DB structure:
id | name | tscore | added
int| string | float(100 or less)| date(2014-01-01 16:34:22)
Code:
while($row = mysql_fetch_assoc($getChartData)){ // Data from MySQL
$added_date = explode(' ',$row['added']); // Date formate 2014-01-01 16:34:22
$chartData[] = array(
'id' => $row['name'],
'tscore' => $row['tscore'],
'added' => $added_date[0] // Here I take the month only
);
}
if($_POST['range'] == 'month'){
foreach($chartData as $key => $value){
$added = explode('-',$chartData[$key]['added']);
$count = 1;
foreach($chartData as $key2 => $value2){
$added2 = explode('-',$chartData[$key2]['added']);
if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){ // if user is the same and the month is the same, add the scores together, increment counter, and unset 2nd instance
$chartData[$key]['tscore'] = ((float)$chartData[$key]['tscore'] + (float)$chartData[$key2]['tscore']);
$count++;
unset($chartData[$key2]);
}
}
$chartData[$key]['tscore'] = ($chartData[$key]['tscore']/$count); // Average all the scores for the month.
}
}
The problem is this method is deleting all the elements of the $chartData array. What can I try to resolve this?
You should try to solve it with MySQL. Try something like this (replace 'your_scores_table' with your table name):
SELECT
Score.name,
AVG(Score.tscore) AS `avg`,
CONCAT(YEAR(Score.added), '-', MONTH(Score.added)) AS `year_month`
FROM
your_scores_table AS Score
GROUP BY
Score.name ASC,
YEAR(Score.added) DESC,
MONTH(Score.added) DESC
;
Your logic is wrong. You are looping through the same array twice. Which means that the following if will always evaluate to true which means that array item will always get unset
//This will always be true
if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){
It may be simpler for you to create another array where you keep your scores. Something like
$aScores = array();
$count = 1;
foreach($chartData as $key => $value){
//Add score to a different array
$aScores[$value['name']]['tscore'] = (($aScores[$value['name']]['tscore'] + $value['tscore']) / $count);
$count++;
}
Also I would look into the MySQL AVG function. You could use that to save you having to do it in PHP

How to get recursively all analogs from table by an article?

I've create a simple table of analogs:
+----+-------+-------+
| id | sku_1 | sku_2 |
+----+-------+-------+
| 1 | a1 | abcd |
| 2 | a2 | a3 |
| 3 | a3 | a1 |
+----+-------+-------+
3 rows in set (0.00 sec)
What it mean? It mean that product with article abcd has an analog with article a1, otherwise for example product with article a3 has an analog with article a1.
How to recursively get all the products from this table by a single article?
My solutions is wrong:
// Small Class to get analogs of products
class Analogs {
public function get_analogs($sku)
{
if (!$sku) return false;
$link = mysql_connect('localhost','','');
mysql_select_db('test');
$sku = mysql_real_escape_string($sku,$link);
$query = mysql_query("SELECT * FROM analogs WHERE sku_1='".$sku."' OR sku_2='".$sku."'");
while($analogs[]=mysql_fetch_assoc($query))
continue;
return $analogs;
}
public function MixedAnalogs($sku)
{
if (!$sku) return false;
$link = mysql_connect('localhost','','');
mysql_select_db('test');
$sku = mysql_real_escape_string($sku,$link);
$query = mysql_query("select sku_1 sku from analogs where sku_2 = '$sku' UNION
select sku_2 sku from analogs where sku_1 = '$sku'");
while($analogs[]=mysql_fetch_assoc($query))
continue;
return $analogs;
}
}
$mixed_analogs = AnalogsMix('abcd',$ids=array());
echo "<pre>";
print_r($mixed_analogs);
echo "</pre>";
// Recursive function to get analogs of analog
function AnalogsMix($sku,$ids=array())
{
$class_analogs = new Analogs();
$analogs = $class_analogs->get_analogs($sku);
foreach ($analogs as $analog)
{
$cross = null;
if ($analog['sku_1']==$sku)
{
$cross->sku = $analog['sku_2'];
}
else
{
$cross->sku = $analog['sku_1'];
}
$cross->id = $analog['id'];
if (!in_array($analog['id'],$ids))
{
$ids[] = $analog['id'];
$mixed[] = AnalogsMix($cross->sku,$ids);
}
}
if (isset($mixed))
{
return $mixed;
}
else
{
return false;
}
}
SQL UNION
select sku_1 sku from analogs where sku_2 = $yourid
union
select sku_2 sku from analogs where sku_1 = $yourid
Then you will get in results only ids of analogs.
Here, I suppose you have all your pairs in an array. For example, for your example, you would call analogsOf(array(array("a1", "abcd"), array("a2", "a3"), array("a3", "a1")), "abcd").
The idea is that you build a list of analogs containing initially only the string you are looking for and, every time you find an analog, you add it to the list of analogs and reiterate. You do so until you iterated the whole array of pairs without finding anything new.
function analogsOf(array $pairs, $key) {
$res = array($key); // The result, with only the given key
$i = 0; // Index of the current item
$changed = false; // Have we added an item to $res during that iteration ?
while ($i < count($pairs)) {
$current = $pairs[$i];
foreach ($res as $item) {
if (($current[0] === $item) && (!in_array($current[1], $res)) {
$res[] = $current[1];
$i = 0; // Reiterate as $res changed
}
else if (($current[1] === $item) && (!in_array($current[0], $res)) {
$res[] = $current[0];
$i = 0; // Reiterate as $res changed
}
else {
$i++; // Nothing found here, go to next item
}
}
}
return $res;
}
Note that this code was NOT tested, so there might be a few bugs here and there, but you've got the idea. Also note that I considered you could put the whole database content in an array, but that is probably not possible for obvious reasons, so you will probably have to adapt the code above.
I found a solution for this problem but the main problem in this approach is that.
it can make a loop like abcd->a1,a1->a3,a3->a2,a2->abcd. and it make recursive function endless and php throw an error. so you have to check for that if it is a big project.
in my solution i consider it parent-> child relation. and if a child found make it parent and check again and so on until there is no result.
let abcd is parent and after first execution a1 is child and relation is abcd->a1. but in next call a1 is parent and from first row of table it give a new relation that is a1->abcd and loop is endless.
To prevent checking in same row i use ID of last row from database and it now check row where id != ID (always check other row)
this is function i write, convert it according to your class and store the value in array as you like. I use a string only.
i knew it not a good solution but i works fine.
<?php
mysql_connect('localhost','','');
mysql_select_db('test');
function getSku($sku, $id, $rel = '') {
$query = mysql_query("SELECT * FROM analogs WHERE sku_1 = '$sku' AND id != '$id'" );
if (mysql_num_rows($query)) {
$row = mysql_fetch_assoc($query);
$sku = $row['sku_2']; //PARENT SKU
$id = $row['id']; //LAST ID
$rel .= $row['sku_1']. '-->' . $row['sku_2']. "<br>";
} else {
$query = mysql_query("SELECT * FROM analogs WHERE sku_2 = '$sku' AND id != '$id'" );
if (mysql_num_rows($query)) {
$row = mysql_fetch_assoc($query);
$sku = $row['sku_1']; //PARENT SKU
$id = $row['id']; //LAST ID
$rel .=$row['sku_2']. '-->' . $row['sku_1']. '<br>';
} else {
return (string)$rel; //NOTHING FOUND
}
}
return getSku($sku,$id,$rel);
}
echo $new = getSku('abcd','-1');

Categories