Multidimensional PHP array from SQL, for json_encode - php

I'm struggling trying to create a three-dimensional array from my DB, and encoding it to JSON.
My DB contains 3 tables, timeline_table, content_table and pic_table. I want the following structure for my JSON:
{"timeline:"{"content":{"pictures:"{}}}}
Here's my current PHP code:
$get = 1;
$results = mysql_query("
SELECT timeline_table.*, content_table.*, pic_table.*
FROM timeline_table
JOIN content_table
ON content_table.tl_ID = timeline_table.tl_ID
JOIN pic_table
ON pic_table.content_ID = content_table.content_ID
WHERE timeline_table.tl_ID = $get
") or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
);
$timeline['timeline']['content'][] = array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
);
$timeline['timeline']['content']['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($timeline));
}
I have also tried with 1 query for each table, and using 3 while loops to fill the array. I believe one query is the better way to go, but please correct me if I'm wrong. This php gives me the following JSON:
{
"timeline":{
"0":{
"tl_ID":"1",
"tl_name":"Tidslinje 1",
"tl_date":"2013-01-16",
"tl_desc":"Test av tl_table"
},
"content":{
"0":{
"content_ID":"1",
"tl_ID":"1",
"content_time":"16:00:00",
"content_date":"2013-01-17",
"content_title":"Test",
"content_content":"Test content number one.",
"content_category":"test",
"content_mapLat":null,
"content_mapLng":null,
"content_zoomLvl":null
},
"pictures":[
{
"pic_ID":"1",
"content_ID":"1",
"pic_path":"http://i.imgur.com/F6RmDFt.jpg",
"pic_desc":"katt",
"pic_link":"http://i.imgur.com/F6RmDFt.jpg"
},
{
"pic_ID":"3",
"content_ID":"3",
"pic_path":"http://i.imgur.com/POum7eK.jpg",
"pic_desc":"seamonster",
"pic_link":"http://i.imgur.com/POum7eK.jpg"
}
]
}
}
}
All pictures regardless of content_ID comes in one array, and if I add more content, contents with ID 2,3 etc comes under the picture array. I want the pictures in arrays under the content_ID they belong to, and the content under the timeline they belong to. I also want the array keys to be "timeline", "content" and "pictures", instead of integers.
Hopefully this is understandable, any help is greatly appreciated!
EDIT: Solved!
$get = 1;
$result = mysql_query("
SELECT t.tl_ID, t.tl_name, t.tl_date, t.tl_desc, c.content_ID, c.content_time, c.content_date, c.content_title, c.content_content, c.content_category, p.pic_ID, p.pic_path, p.pic_desc, p.pic_link
FROM timeline_table t
LEFT JOIN content_table c ON t.tl_ID = c.tl_ID
LEFT JOIN pic_table p ON c.content_ID = p.content_ID
WHERE t.tl_ID = $get
ORDER BY t.tl_ID, c.tl_ID, p.content_ID
") or die(mysql_error());
$jsonData = array();
$tl_ID = 0;
$content_ID = 0;
$timelineIndex = -1;
$contentIndex = -1;
while($row = mysql_fetch_assoc($result)){
if($tl_ID != $row['tl_ID']){
$timelineIndex++;
$contentIndex = -1;
$tl_ID = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_ID'] = $row['tl_ID'];
$jsonData[$timelineIndex]['tl_name'] = $row['tl_name'];
$jsonData[$timelineIndex]['tl_date'] = $row['tl_date'];
$jsonData[$timelineIndex]['tl_desc'] = $row['tl_desc'];
$jsonData[$timelineIndex]['content'] = array();
}
if($content_ID != $row['content_ID']){
$contentIndex++;
$content_ID = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_ID'] = $row['content_ID'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_time'] = $row['content_time'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_date'] = $row['content_date'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_title'] = $row['content_title'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_content'] = $row['content_content'];
$jsonData[$timelineIndex]['content'][$contentIndex]['content_category'] = $row['content_category'];
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'] = array();
}
$jsonData[$timelineIndex]['content'][$contentIndex]['pictures'][] = array(
'pic_ID' => $row['pic_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
}
echo stripslashes(json_encode($jsonData));
}

Edited, try this one:
$timeline['timeline'][] = array(
'tl_ID' => $row['tl_ID'],
'tl_name' => $row['tl_name'],
'tl_date' => $row['tl_date'],
'tl_desc' => $row['tl_desc'],
'content' => array(
'content_ID' => $row['content_ID'],
'tl_ID' => $row['tl_ID'],
'content_time' => $row['content_time'],
'content_date' => $row['content_date'],
'content_title' => $row['content_title'],
'content_content' => $row['content_content'],
'content_category' => $row['content_category'],
'content_mapLat' => $row['content_mapLat'],
'content_mapLng' => $row['content_mapLng'],
'content_zoomLvl' => $row['content_zoomLvl'],
'pictures' => array(
'pic_ID' => $row['pic_ID'],
'content_ID' => $row['content_ID'],
'pic_path' => $row['pic_path'],
'pic_desc' => $row['pic_desc'],
'pic_link' => $row['pic_link']
);
);
);

Related

Problems with mysqli_fetch_array

I want to put the result of my request in this array, $dataPoints1 = array, but it doesn't work.
This is my request:
$sql = "
SELECT COUNT(id_etudiant)as nbre1 FROM suivre WHERE n_formation='1'
UNION
SELECT COUNT(id_etudiant)FROM suivre WHERE n_formation='2'
UNION
SELECT COUNT(id_etudiant)FROM suivre
WHERE n_formation='3'";
$result = mysqli_query($link,$sql);
while($row = mysqli_fetch_array($result)) {
$dataPoints1 = array(
array("y" => ''. $row["nbre1"].'',"label" => "formation1" ),
array("y" => ''. $row["nbre1"].'',"label" => "formation2" ),
array("y" => ''. $row["nbre1"].'',"label" => "formation3" ),
);}
You can start by simplifying your sql
SELECT COUNT(id_etudiant)as nbre1, n_formation as formation FROM suivre GROUP BY n_formation;
Start by declaring your array outside of your loop then add to the next index by using the "[]".
Try this:
$dataPoints1 = array();
while($row = mysqli_fetch_array($result)) {
$dataPoints1[] = array("y" => $row["nbre1"], "label" => $row['formation'] )
or
$dataPoints1[] = $row
}

Nested While Loop not working

I am developing a webservice for and android app the webservice is in PHP fetching data from a MySQL database ... The problem that I am having is that some of the projects have multiple details but my code is only fetching one detail for every project. I am getting the data in JSON format.
You can check this Here
Here is my code
function requiredData(){
$db = $this->dbConnection();
//$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$sql = "SELECT * FROM projects";
$queryResult = $db->query($sql);
if($queryResult->num_rows > 0){
while($row = $queryResult->fetch_assoc()){
$pid = $row['project_id'];
$detailsql = "SELECT * FROM project_details WHERE project_id=$pid";
$sqlResult = $db->query($detailsql);
if($sqlResult->num_rows > 0){
while ($d = $sqlResult->fetch_assoc()){
$r = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
}
$results[$row['project_name']] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"project_work_details" => $r
);
}
}
return $results;
}
Thanks in advance for your help
The issue is in the second while loop. You are assigning array to $r, and $r value overwrites every time.
So, I am assigning now array to an other array, So it will become 2 dimensional array, like this;
while ($d = $sqlResult->fetch_assoc()){
$r[] = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
Now you can use $r, it will have multiple details of the project.

Looping through character data and items from MySQL DB in PHP

I have the following code:
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
while($char = mysql_fetch_array($charQ))
{
$chars[] = $char;
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
while($item = mysql_fetch_array($itemQ))
{
$itemData[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$charData[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $itemData);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $charData);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>
I have successfully loaded character data from the table 'dr_chars' in my database. I'm trying to load the corresponding item data from the retrieved character ID and push it into the $charData array. So I can then easily encode & output it in a JSON format.
If my question isn't clear just ask and I'll try to explain the situation better. The JSON data is being outputted into flash for dynamic use.
I managed to fix this final code as follows:
<?php
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
$chars = array();
while($char = mysql_fetch_array($charQ))
{
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
$items = array();
while($item = mysql_fetch_array($itemQ))
{
$items[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$chars[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $items);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $chars);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>

Fetch array using both if and while doesn't work

Basically I have 2 methods in the same class, getMovie and getGenres. They are very similar but One doesn't return what I expect.
Here's getMovie method:
public function getMovie($argType, $arg){
$movieQuery = "SELECT id,
rt_id,
imdb_id,
url,
rt_url,
type,
adult,
DATE_FORMAT(release_date, '%Y') AS year,
date_added,
title,
runtime,
budget,
revenue,
homepage,
rating,
tagline,
overview,
popularity,
image,
backdrop,
trailer
FROM movies
WHERE " . $argType . " = " . $arg;
$movieResult = $this->_query($movieQuery);
$movies = array();
if($movieResult->fetch_array(MYSQLI_ASSOC)){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
$movies[] = array( 'title' => $m['title'],
'duplicate' => $m['duplicate'],
'url' => $m['url'],
'rt_url' => $m['rt_url'],
'release_date' => $m['release_date'],
'date_added' => $m['date_added'],
'type' => 'movie',
'adult' => $m['adult'],
'id' => $id,
'rt_id' => $m['rt_id'],
'imdb_id' => $m['imdb_id'],
'rating' => $m['rating'],
'tagline' => $m['tagline'],
'overview' => $m['overview'],
'popularity' => $m['popularity'],
'runtime' => $m['runtime'],
'budget' => $m['budget'],
'revenue' => $m['revenue'],
'homepage' => $m['homepage'],
'image' => $m['image'],
'backdrop' => $m['backdrop'],
'trailer' => $m['trailer'] );
}
return $movies;
}
else{
return false;
}
Here's getGenres method:
public function getGenres($movieId = NULL){
$genresQuery = "";
if($movieId != NULL){
$genresQuery = "SELECT id,
name
FROM genres
WHERE id = ANY (
SELECT genre_id
FROM movie_genres
WHERE movie_id = " . $movieId . ")";
}
else{
$genresQuery = "SELECT id,
name
FROM genres";
}
$genresResult = $this->_query($genresQuery);
$genres = array();
if($genresResult->fetch_array(MYSQLI_ASSOC)){
while($genre = $genresResult->fetch_array(MYSQLI_ASSOC)){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
else{
return false;
}
}
And here's how I call them:
$mov = $movie->getMovie(2207);
print_r($mov); // output: Array()
$gen = $movie->getGenres(2207);
print_r($gen); // output: Array(values inside)
Both queries do actually return expected values but getMovies method doesn't work with the if statement. It works fine if I just have while loop.
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this? If there is indeed a reason to use an if statement as well as wile loop then why doesn't it work with getMovies method?
Edit 1: I tried storing the array like so but that resulted in a memory related error:
$r = $genresResult->fetch_array(MYSQLI_ASSOC);
if($r){
while($r){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this?
No, according to the php manual mysqli_result::fetch_array returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.
Null is falsy so the while loop will not be entered.
Although the if statement is unnecessary if you had one you would use mysqli_result::$num_rows to check if the query returned any rows.
if($movieResult->num_rows > 0){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
...
}
}

Dividing rows into dimensional array

I want to get the list for the food from the database into array order by category so that I can split each entry into the categories.
Like this..
$menu = array(
'Appetizers' => array(
'Chicken Tenders' => '$2.99',
'Twisted Chips' => '$1.99'
),
'Seafood' => array(
'Bayou Tilapia' => '$4',
'Grill Atlantic Salmon' => '$3.99'
),
'Steaks & Combos' => array(
'Cowboy Grande Sirloin' => '$7.99'
)
)
Here is what I did.
$db->Query("SELECT menuTitle,menuCategory,menuPrice FROM menu");
$menu = array();
while ($row = $db->Row()) {
$a = array($row->menuCategory => array($row->menuTitle=>$row->menuPrice));
array_push($menu,$a);
}
It doesn't seem to work. Would you please advise how to achieve this?
replace:
$a = array($row->menuCategory => array($row->menuTitle=>$row->menuPrice));
array_push($menu,$a);
with:
$menu[$row->menuCategory][$row->menuTitle]=$row->menuPrice;
The code in the while block is not exactly seeming right, as you always redefine the $a array while iterating.
while ($row = $db->Row()) {
$a[ $row->menuCategory ][ $row->menuTitle] = $row->menuPrice;
array_push($menu,$a);
}
This way, you will only append new keys to the array.
$db->Query("SELECT menuTitle,menuCategory,menuPrice FROM menu");
$menu = array(); $a = array();
while ($row = $db->Row()) {
$a[$row->menuCategory ][$row->menuTitle] = $row->menuPrice;
}
array_push($menu,$a);
echo "<pre>";print_r($menu);echo "</pre>";

Categories