Sorry for bad english and bad title!
I have the table "post"
id title
1 test Thread
2 hello
3 just
so have "tags"
tagid tagname
1 test
2 russia
3 new site
so have a post_tags
tagid postid
1 1
2 1
3 1
I need an array from var_dump next below:
$posts = array(
1 => array(
'title' => 'test Thread',
'tags' => array(
'test', 'russia', 'new site',
),
),
2 => array(
'title' => 'hello',
'tags' => NULL
),
3 => array(
'title' => 'just',
'tags' => NULL
),
)
I trying do it, but i getting not that what i want.
SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`
I getting in SQL next following:
id title tagname
1 test Thread test
1 test Thread russia
1 test Thread newsite
2 hello NULL
3 just NULL
PHP
$query = mysql_query("SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`");
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
$posts[] = $row;
}
var_dump($posts);
Thank you!!!
The query is fine. You just need some logic in your loop:
while ($row = mysql_fetch_assoc($query))
{
if (isset($posts[$row['id']])) {
$posts[$row['id']]['tags'][] = $row['tagname'];
}
else {
$posts[$row['id']] = array(
'title' => $row['title'],
'tags' => $row['tagname'] === null ? null : array($row['tagname'])
);
}
}
If you have already seen a row with the same post id then all you want from the current row is the tag name (so add this to the "tags" array). If it's the first time a row with this post id is seen just add it to $posts, being a little careful to set "tags" to either null or an array with one element.
you cannot get a multi-dimensional arrays back from a mysql database. you must do your own post processing to the results if you want it in that form. Something like this maybe?
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
if (!isset($posts[$row['id']])) {
$posts[$row['id']] = array();
$posts[$row['id']]['title'] = $row['title'];
$posts[$row['id']]['tags'] = array();
}
if ($row['tagname'] != null) $posts[$row['id']]['tags'][] = $row['tagname'];
}
Try this:
while ($row = mysql_fetch_assoc($query))
{
if( !isset( $posts[$row["id"]] ) ) {
$posts[ $row["id"] ] = array( "title" => $row["title"], "tags" => array() );
}
array_push( $posts[ $row["id"] ][ "tags" ], $row["tagname"] );
}
I can't debug it, so tell me if you get any errors
Related
I need to create a SQL query and the PHP code to enter this data into JSON format for a pie chart using Google Charts API.
+--------+---------+---------+---------+
| City | P1 | P10 | P25 |
+--------+---------+---------+---------+
|Dubai | 45| 135| 136|
|SanDiego| 23| 34| 45|
|SanFran | 37| 39| 28|
+--------+---------+---------+---------+
This is the query I have already tried:
<?php
$rows2 = array();
$table2 = array();
$query2 = 'SELECT AVG(`P1`) AS avg_p1, AVG(`P10`) AS avg_p10, AVG(`P25`) (SELECT `P1`, `P10`, `P25`
FROM `INFORMATION_SCHEMA`.`COLUMNS` AS pmname
WHERE `TABLE_SCHEMA`='g1109689'
AND `TABLE_NAME`='realtime') AS avg_p25 FROM `realtime` WHERE `City`="Dubai"';
$result2 = mysqli_query($conn, $query2);
$table2['cols'] = array(
array(
'label' => 'PM Type',
'type' => 'string'
),
array(
'label' => 'PM Number',
'type' => 'number'
)
);
while($row2 = mysqli_fetch_array($result2))
{
$sub_array2 = array();
$sub_array2[] = array(
"v" => $row2["avg_p1"]
);
$sub_array2[] = array(
"v" => $row2["avg_p10"]
);
$sub_array[] = array(
"v" => $row2["avg_p25"]
);
$rows2[] = array(
"c" => $sub_array2
);
}
$table2['rows'] = $rows2;
echo $jsonTable2;
?>
I want the categories for the pie chart to be the averages of P1, P10, P25, respectively. So how do I create a SQL statement to select the averages and the name of the columns and how do I put that into a JSON table? Thanks!
I am guessing that you want average rowwise i.e. adding (p1+p10+p25)/3 for every city and not columnwise. So you can try the below query-
select city,(tablename.p1 + tablename.p10 + tablename.p25) / 3 as average from tablename
If you want to calculate avg columnwise for everycity you can use avg() method of sql.
select city, avg(p1),avg(p10),avg(p25) from tablename;
PS: you will only get name of one city if you use avg() function
I am learning Api development where i want to retrieve data from two tables
First table (items) contains:
id, feed_id, title, author, content
Second table (feeds):
feed_id,title,url
I want to get Json response like:
{
- stories :
[
id
feed_id {
title,
url
}
title
author
]
}
My PHP function to retrieve story biased on id is like:
$app->get('/stories/:id', 'authenticate', function($story_id) {
$response = array();
$result = Database::get('db')->table('items')
->eq('rowid', $story_id)
->findOne();
//$response["error"] = false;
if ($result != NULL) {
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => $result["feed_id"],
'title' => $result["title"],
'isBreaking' => $result['isBreaking'],
'author' => $result['author'],
'updated' => $result["updated"],
'url' => $result['url'],
'content' => $result["content"]);
echoRespnse(200, $response);
}
else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The result i get is like:
{
- "stories": [
{
id
feed_id
title
url
}
]
}
How can i retrieve data from the second tablet (feeds) biased on feed_id and get the data into sub array?
as #MikeBrant mentioned you have to use join between two tables to retrieve correct data. the plain query will be something like this:
select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id
and then change your $response['stories'] like this:
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
'title' => $result["feed_title"],
'url' => $result["url"]
),
'title' => $result["title"],
.
.
.
);
you get the idea :)
My table looks like:
id | title | link | kind
------------------------
1 link1 http one
4 link2 http two
2 link9 http one
I want to give back a JSON Array (JSON parsing is not the problem!) which looks like:
one
- link1, http
- link9, http
two
- link2, http
The kind-colum is dynamic so I do not know the actual string. (But it is never (null)!)
What I have:
$links = array();
while($row = mysql_fetch_object($result)) {
$link = array(
'title' => $row->title,
'link' => $row->link,
'kind' => $row->kind
);
$links[] = $link;
}
echo json_encode($links);
That's one array with all columns for each element.
Use $row->kind as an index into the top level array.
$kinds = array('one' => 1, 'two' => 2, ...etc...);
$links = array();
while($row = mysql_fetch_object($result)) {
$link = array(
'title' => $row->title,
'link' => $row->link
);
$links[$kinds[$row->kind]][] = $link;
}
echo json_encode($links);
You can do this in MySQL query:
SELECT CONCAT("[",
GROUP_CONCAT(
CONCAT("{".kind.":'",title ,"'"),
CONCAT(",".kind.":'",link),"'}")
)
,"]") AS json
FROM table_name;
This is the query I use:
$idList="32,33,21,11";
$query = "SELECT post_id, meta_value FROM wp_posts
WHERE meta_key = 'grade' AND post_id IN ($idList)";
As a result, the where clause become keys:
$result = array(
0 => array('post_id'=> 32, 'meta_value'=>5),
1 => array('post_id'=> 33, 'meta_value'=>2),
2 => array('post_id'=> 21, 'meta_value'=>8),
)
I desire to have a result like this:
$result = array(
0 => array( 32 => 5 ),
1 => array( 33 => 2 ),
2 => array( 21 => 8 ),
)
How to achieve this? Thanks!
Loop through the result set like this:
$_final = array(); // new result set
foreach ($result as $value)
$_final[] = array($value['post_id'] => $value['meta_value']);
unset($result); // free memory from old result set
UPDATE: If there are too many element and you afraid of memory consumption, you can do it the following way:
$_final = array(); // new result set
foreach ($result as $key => $value) {
$_final[] = array($value['post_id'] => $value['meta_value']); // composing new data
unset($result[$key]); // unsetting already parsed value
}
unset($result); // freeing memory from old result set
Hey guys I'm trying to learn codeigniter, but once again I'm STUCK and I seek help (as usual :P )
What I need to do?
-> I need to get the data related to a article from the database along with other stuff like the tags for the article and all the comments. I'm thinking of keeping single level nested comments for the article.
Well I'm done with the tag part [link to the answer which helped me with the same : Returning and using multidimensional array of records from database in CodeIgniter 2.0 ] but the comment part is driving me nuts.
Well to get started here is my comments table
Comments
+---------------+-------------+
| Field | Type |
+---------------+-------------+
| commentId | int(10) |
| PostId | int(10) |
| author | varchar(30) |
| email | varchar(30) |
| url | varchar(50) |
| date | datetime |
| comment | text |
| parent | int(10) |
+---------------+-------------+
I'm using the parent field to keep a track of the parent for a nested child comment. By default the value is 0 which means it the parent. Child comment will have the commentid of its parent comment
public function getPost($postName = NULL , $year = NULL, $month = NULL ){
if($postName != NULL && $year != NULL && $month != NULL){
//single post
$this->load->model('comment_model');
$this->db->where('postName',$postName);
$this->db->where('year(date)',$year);
$this->db->where('month(date)',$month);
$q = $this->db->get('mstack_Post');
if($q->num_rows()>0){
$post = $q->result();
foreach ($post as &$p) {
$p->tags = $this->getAllTags($p->postId);
/* getting the comments */
$com = $this->comment_model->getComments($p->postId);
/*echo count($com).' is the total count'; output= 4 */
foreach ($com as &$c) {
/* trying to filter the comment. but all I get is 1 comment as the output*/
if($c->parent==0){
$p->comments->parentComment = $c;
}elseif($c->commentId==$c->parent){
$p->comments->childComment = $c;
}
}
}
return $post;
}else{
return array();
}
}
}
Any help will surely be appreciated.
If you have any other technique /idea to display multi level comments then do let me know. :)
Here is the solution that might be helpfull:
First you need 2 helper recursive function:
// Building comments.
function buildComments($list, $parent = 0)
{
// Creating result array.
$result = array();
//looping...
foreach ($list as $item)
{
//iteration starts with 0 as default.
if ($item->parent == $parent)
{
// add to the result
$result[$item->commentId] = array(
'author' => $item->author,
// ... other definitions
'child' => buildComments($list, $item->commentId) //execute this function for child.
);
}
}
return $result;
}
function printComments($arg, $depth = 1)
{
foreach ($arg as $item)
{
// Printing comment...
echo str_repeat(' ', $depth) . $item['author'] . "<br />\r\n";
// extra echoes...
// if it has a child comment...
if (count($item['child'] > 0))
{
printComments($item['child'], $depth + 1);
}
}
}
A little explaining:
The buildComments() function will starts with rows that parents has 0. Then it will execute itself for child. if child as a child, it will add it. In the end, result will be like this:
$result = array(
1 => array(
'author' => 'John',
'child' => array(
8 => array(
'author' => 'Jane',
'child' => array(
3 => array(
'author' => 'Jamie',
'child => array()
)
)
),
6 => array(
'author' => 'Jackie',
'child => array()
),
9 => array(
'author' => 'Harry',
'child => array()
)
)
),
4 => array(
'author' => 'Jack',
'child' => array()
),
10 => array(
'author' => 'Clark',
'child' => array(
11 => array(
'author => 'Lois',
'child' => array()
)
)
),
12 => array(
'author' => 'Luthor',
'child' => array()
)
);
In the printComments() function we are printing results recursive. for each child, function repeats itself. You will get result like this:
John
Jane
Jamie
Jackie
Harry
Jack
Clark
Lois
Luthor
For more information about recursive functions Look this answer
USAGE
$this->db->where('postName',$postName);
$this->db->where('year(date)',$year);
$this->db->where('month(date)',$month);
$this->db->order_by('parent', 'asc');
$query = $this->db->get('comments');
$comments = buildComments($query->result());
printComments($comments);
that'is that simple...