I am trying to make an array with posts in them, now, i need to insert the posts into the array based on their post date, eg if a post was posted on day 4 it will come after the post that was posted on day 5, so the newest posts gets added and displayed first, is there a good way to do this?
The easiest and not right method at all:
$sortedNews = []; //sorted news
foreach($newsArray as $news) {
$sortedNews[strtotime($news['date'])] = $news; //take date and switch to unix timestamp as key of value
}
krsort($sortedNews); //sort by key (reverse) new to old
The right way it's let your database sort it itself ORDER BY `date` DESC
Related
Below I have stripped down my code to a simplified version. I am storing SQL SELECT results for:
last name (dlname)
category (category)
date this data was added to database (date_added)
clients name (client)
I have appended an additional field outside the SQL SELECT called 'days_on_list'. This field shows the number of days since the data was added to the database, making the table output 5 columns of user data. ALL 5 COLUMNS ARE TO BE SORTABLE.
I am using server-side JSON and have successfully been able to display this to the table and perform sorting on 4 of the 5 columns. The problem is that I am unable to sort the 'days_on_list' field as the PHP file containing the SQL code only allows me to sort the 4 fields from the select query. Is there a way I can make 'days_on_list' column be sortable in the table? I know I can add this field to the sql table, but I would have to run a scheduled event on the server to update this daily (which I am not comfortable with).
Is there another way to allow for this kind of flexible table sorting?
Sorry about the question title (may be confusing), I was having trouble putting this into a question.
/*SQL CODE ABOVE HERE STORES SELECT RETURNS IN $result*/
$cart = array();
$i = 0; //index the entries
// get variables from sql result.
if ($num_rows > 0) { //if table is populated...
while ($row = mysqli_fetch_assoc($result)) {
//calculate days on list by getting the number of days from
//the 'date_added' to today
$date1 = date_create($row['date_added']);
$today = date_create(date("d-m-Y"));
$interval = date_diff($date1, $today);
$doty = $interval - > format("%a");
$cart[$i] = array(
"dlname" => htmlspecialchars($row['dlname']),
"category" => htmlspecialchars($row['category']),
"date_added" => htmlspecialchars($row['date_added']),
"client" => htmlspecialchars($row['client']),
"days_on_list" => $doty, //date_added to now
);
$i = $i + 1; //add next row
}
//encoding the PHP array
$json_server_pagination_data = array(
"total" => intval($num_rows),
"rows" => $cart, //array data
);
}
echo json_encode($json_server_pagination_data);
Because days_on_list is calculated by simply comparing date_added to the current date, sorting by days_on_list should have exactly the reverse effect as sorting by date_added.
In other words, you don't actually need to sort by days_on_list. If the user selects days_on_list as the sort column, just use ORDER BY date_added (in the opposite direction ASC/DESC).
I have a array of events with unixtimestamp and i want to show them according to year. Mean section wise.
2015
Event 1
Event 2
Event 3
2014
Event 1
Event 2
Event 3
What i do:
$yearlyEvents=array();
foreach ($events as $event) {
$eventPost = get_post($event->post_id);
$timestamp=$event->start;
$eventYear=gmdate("Y", $timestamp);
if($index=in_array($eventYear, $yearlyEvents, true)){
print_r($index);
}
else{
$tempObj['name']=$eventYear;
$tempObj['events']=$event;
$yearlyEvents[]=$tempObj;
}
}
But not get the desired results.Anybody help?
You need to get events as sub arrays of year.
Add sub arrays, one for each year append events to it.
This is my preferred logic, please feel free to change it in accordance with your project needs.
Corrected Code:
$yearlyEvents=array();
foreach ($events as $event) {
$eventPost = get_post($event->post_id);
$timestamp=$event->start;
$eventYear=gmdate("Y", $timestamp);
if($index=in_array($eventYear, $yearlyEvents, true)){
print_r($index);
}
else{
$tempObj['name']=$eventYear;
$tempObj['events']=$event;
$yearlyEvents[$eventYear][] = $tempObj; // Check here.
}
}
first of all you need to get result from Database in such a format which is easy to manipulate for your output.
Here you are trying to display events years wise in descending order and events in ascending order. So first of all get result from database like
SELECT * FROM events ORDER by events.start DESC,events.post_id ASC
Now it is in an order which is easy to display. loop through and display result until next year found. check if next year come display year too.
I am trying to get a row which have latest created time,
Example, i have table with news_id, news_content, news_postedon. This table have 10 rows of data,
Now i want to pull row which have latest time of new_postedon,
I am using codeigniter,
I added below code,
function view_latestnews()
{
$this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
$this->db->select_max('news_postedon');
return $this->db->get('sc_news')->row();
}
By using this function i got only value of news_posted on which is max like (stdClass Object ( [news_postedon] => 2015-04-12 21:28:21 )),
But i could not get value of news_content
How can i get complete row which have latest time of posted using codeigniter?
Thanks in advance
Try
function view_latestnews()
{
$this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
$this->db->where('news_postedon = (SELECT max(news_postedon) FROM sc_news)');
return $this->db->get('sc_news')->row();
}
Current situation
I have two tables in my database, one for posts, and one for ratings. These are linked with a relation in the MySQL so that one post may have 0, 1 or multiple ratings, but one rating can only be applied to one post.
When I fetch a list of posts, I also want to get ratings, but without having to make a separate call to the database for each post in the foreach loop.
To do this I have attempted to use an SQL query to fetch all posts with a LEFT JOIN on ratings so that it will return a result like this:
statusId|statusBody|rating
-----------------------------
1, post1, 0
1, post1, 1
2, post2, 0
3, post3, 1
3, post3, 1
The SQL works fine, and I get the data I ask for.
Ideally what I am trying to achieve now is to turn this table into a collection of objects, with each object storing the post information as well as a value depending on it's total ratings.
After using PDO to return the data result, this is the code I am using to map the data:
Code Logic
The logic of my code goes like this:
Get all statuses joined with ratings table
Create empty output array
Loop through PDO result
{
Create loop specific temp array
Push first row of result into temp array
Remove row from PDO result
Loop through PDO result for objects with matching statusId
{
If row matches statusId, add to temp buffer and remove from PDO result
}
Take first row of buffer and create status object
Loop through objects in temp array to calculate ratings and add onto above status object
Clear temp buffer
Add status object to output array
}
return output array
Actual Code
try
{
$result = $pdo->query($sql);
//if($result == false) return false;
$statuses = $result->fetchAll(PDO::FETCH_CLASS, 'status');
}
catch (PDOException $e)
{
return FALSE;
}
if (!$result) {
return FALSE;
}
//create empty output array to be filled up
$status_output = array();
//loop through all status
foreach($statuses as $s1key => $s1value)
{
//initialise temporary array;
$status_temp_buffer = array();
//create temp array for storing status with same ID in and add first row
array_push($status_temp_buffer, $s1value);
//remove from primary array
unset($statuses[$s1key]);
//loop through array for matching entries
foreach($statuses as $s2key => $s2value)
{
//if statusId matches original, add to array;
if($s2value->statusId == $s1value->statusId)
{
//add status to temp array
array_push($status_temp_buffer, $s2value);
//remove from primary array
unset($statuses[$s2key]);
}
//stop foreach if statusId can no longer be found
break;
}
//create new status object from data;
$statObj = $status_temp_buffer[0];
//loop through temp array to get all ratings
foreach($status_temp_buffer as $sr)
{
//check if status has a rating
if($sr->rating != NULL)
{
//if rating is positive...
if($sr->rating == 1)
{
//add one point to positive ratings
$statObj->totalPositiveRatings++;
}
//regardless add one point to total ratings
$statObj->totalAllRatings++;
}
}
//clear temporary array
$status_temp_buffer = NULL;
//add object to output array
array_push($status_output, $statObj);
}
Problem
The problem I am coming up against with this code is that although the ratings are fine, and it correctly calculates the ratings total for each post, it still shows duplicates where a post has more than one rating.
Any help with this would be greatly appreciated,
Thanks
As i understood it, the goal is to get the total rating of each Post entry. Instead of manually looping over each and every rating, there are two other path you could take:
compute the total in the query:
SELECT SUM(rating) AS total , .. FROM Posts LEFT JOIN .... GROUP BY statusID
You will receive a list of Post entries, each already with total rating calculated. This is a very good solution if you have a lot of writes to to the Ratings table, and much less reads.
the other way is to break the table normalization, but to increase read performance. What you would have to do is to add another column in the Posts table: total_rating. And have an TRIGGER on INSERT in the Ratings table, which changes the Posts.total_rating accordingly.
This way has a benefit of simplifying the request of Posts. At the same time Ratings table can now be use to ensure that total_rating has been calculated correctly, or to recalculate the value, if there are some large changes in the ratings: like banning of user, which results in removing all ratings made by this user.
I have this so far
get_currentuserinfo(); $the_post = get_posts("author=" . $current_user->ID . "&posts_per_page=1"); $the_post = $the_post[0];
but I'm not sure how to get just the ID out of the array
get_posts() will return an array of posts ordered by the date of publication, in descending order. So, with the code you posted, the first post in the array ([0]) will be the last post published by the author. If you really want the first post of the user, you can just add the order argument to the call (&order=ASC) to override the default.
I think the key for the ID is just "ID", so you can retrieve it with $the_post = $post[0]['ID']. But I have to admit I can't remember for sure and the documentation does not detail that, it could also be "post_id". You can do a: print_r($the_post) to check the keys of the returned array.
You can write query like this way-
$oldest_post_query = get_posts("post_type=post&numberposts=1&order=ASC");
$oldest_post_id = $oldest_post_query[0]->ID;
//print the post title
<h1>'.get_the_title( $oldest_post_id ).'</h1>';