Echo the date while using the foreach function to list arrays together

Is there a way to sort articles by Date instead of just Name?

Directory structure:

  • Blog/2019/articleDirA, Blog/2019/articleDirB,...
  • Blog/2018/articleDirA, Blog/2018/articleDirB,...

Each article directory (ex. articleB) contains these files:

  • data.php
  • _counter.txt
  • img/

An example from data.php:

$article = array( 
  'date' => '2019-03-01',
  'headline' => 'Hello BB!'
);
// Determine in which directory the page is located and define the correct path
if ($section === $baseDir): $actualPath = ''; else: $actualPath = '../'; endif; // result: ../;
//////////
function BlogYear() {
  global $section;
  $NewsFeedYear = array();
  $NewsFeedYear = array_filter(glob('*'), 'is_dir'); // Determine directories (2019: articleDirA, articleDirB ...)
  rsort($NewsFeedYear); // Sorts in reverse order: // 2019, 2018, 2017 ...
  $currentYear = basename(getcwd()); // The current year is the last dir from a path in a string (2019)
  $currentYearPath = array_filter(glob('*'), 'is_dir'); // Determine this current year directory (articleA, articleB ...)
  natsort($currentYearPath); // Sorted in natural order, 2019
//////////
echo '<div>';
foreach($currentYearPath as $articleDir_name) {
  require $articleDir_name.'/data.php';
  echo '<article id="'.$articleDir_name.'">
        <header>Article name is: <b>'.$articleDir_name.'</b></header>
        <div>
        <p>Date: <b>'.date("d. m. Y",strtotime($article['date'])).'</b></p>
        <p>Headline: '.$article['headline'].'</p>
        <p>Counter: ';
        global $base_dir;
        $basePath = preg_replace('/lib/', '', $base_dir);
        include $basePath.$section.'/'.$currentYear.'/'.$articleDir_name.'/_counter.txt';
  echo '</p>
       <p>Link: <a href="'.$section.'/'.$currentYear.'/'.$articleDir_name.'">'.$articleDir_name.'</a></p></article>';
}
echo '</div>';
 }
}
BlogYear();

Result in directory 2019

Article name is: articleDirA
Date: 01. 01. 2019
Headline: Hello AA!
Counter: 45
Link: Blog/2019/articleDirA/

Article name is: articleDirB
Date: 01. 03. 2019
Headline: Hello BB!
Counter: 34
Link: Blog/2019/articleDirB/

Article name is: articleDirC
Date: 01. 02. 2019
Headline: Hello CC!
Counter: 67
Link: Blog/2019/articleDirC/

Expected in directory 2019

Article name is: articleDirB
Date: 01. 03. 2019
Headline: Hello BB!
Counter: 34
Link: Blog/2019/articleDirB/

Article name is: articleDirC
Date: 01. 02. 2019
Headline: Hello CC!
Counter: 67
Link: Blog/2019/articleDirC/

Article name is: articleDirA
Date: 01. 01. 2019
Headline: Hello AA!
Counter: 45
Link: Blog/2019/articleDirA/

The problem is that only directory names are being sorted, not the dates within each data.php file.

Answer №1

To start, you can save each li element in an array and use the date as the key. Then, utilize the krsort function to sort the array in descending order based on your needs. The code snippet below demonstrates this approach:

$articleCollection = [];
foreach($currentYearPath as $articleDir_name) {
    require $articleDir_name.'/data.php';
    $articleCollection[strtotime($article['date'])] = 'your data here';
}
krsort($articleCollection);
echo implode("<br/>", $articleCollection);

Make sure to replace "your data here" with your actual content in li format. This method should provide the desired outcome for you.

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, ...

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

Understanding the time complexity of Object.entries()

Is the complexity of Object.entries() in JavaScript known? According to information from this question, it seems like it could possibly be O(n) if implemented by collecting keys and values as arrays and then combining them together? ...

Sorting a list based on user-defined criteria in Ionic 3

Currently working on a project using Ionic and Firebase, I am faced with the task of comparing arrays produced by users with those stored in Firebase. This comparison is essential for filtering a list of products. The user can reorder a list containing 3 ...

Tips for concealing a particular button that shares the same class designation

Is there a way to create a function in vanilla JavaScript that can hide a specific button? <button class"btn">button 1 </button> <button class"btn">button 2 </button> <button class"btn">button 3 </button> Specifically, ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

The error message "ch.match is not a function" appeared in the Javascript code

Here are two functions that I need help with: //Function A var ltrToNato = function(ch) { var x = ch; var nato = ('{"A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India" ...