skip to Main Content

I currently have an array $jobs that contains job data, and this array has a date property called published_at. I want to sort this array by date (published_at) as I’ve been asked to arrange all jobs from the most recent. I tried the code above, but it’s throwing an error. I appreciate the help.

I try this code below, but it throws errors

function compareByPublishedAt($a, $b) {
   $dateA = strtotime($a['published_at']);
   $dateB = strtotime($b['published_at']);
return $dateA - $dateB;
                                 }

usort($jobs, 'compareByPublishedAt'); 

The template with the whole code below

<section id="limestaff-job-search">
    <h3>Job Search</h3>
    <?php require 'top-search.php'; ?>
    <div class="jobs-wrapper">
        <?php if (empty($jobs)): ?>
            <h4>No Jobs Found</h4>
        <?php else: ?>
            <?php $currencies=[["id"=>1,"code"=>"USD","symbol"=>"$"],["id"=>2,"code"=>"EUR","symbol"=>"€"],["id"=>3,"code"=>"JPY","symbol"=>"¥"],["id"=>4,"code"=>"GBP","symbol"=>"£"],["id"=>5,"code"=>"AUD","symbol"=>"A$"],["id"=>6,"code"=>"CAD","symbol"=>"C$"],["id"=>7,"code"=>"CHF","symbol"=>"CHf"],["id"=>8,"code"=>"CNY","symbol"=>"元"],["id"=>9,"code"=>"SEK","symbol"=>"kr"],["id"=>10,"code"=>"NZD","symbol"=>"NZ$"],["id"=>11,"code"=>"MXN","symbol"=>"$"],["id"=>12,"code"=>"SGD","symbol"=>"S$"],["id"=>13,"code"=>"HKD","symbol"=>"HK$"],["id"=>14,"code"=>"NOK","symbol"=>"kr"],["id"=>15,"code"=>"KRW","symbol"=>"₩"],["id"=>16,"code"=>"TRY","symbol"=>"₺"],["id"=>17,"code"=>"RUB","symbol"=>"₽"],["id"=>18,"code"=>"INR","symbol"=>"₹"],["id"=>19,"code"=>"BRL","symbol"=>"R$"],["id"=>20,"code"=>"ZAR","symbol"=>"R"],["id"=>21,"code"=>"CZK","symbol"=>"Kč"],["id"=>22,"code"=>"ILS","symbol"=>"₪"],["id"=>23,"code"=>"PLN","symbol"=>"zł"],["id"=>24,"code"=>"AED","symbol"=>"إ.د"],["id"=>25,"code"=>"SAR","symbol"=>"﷼"],["id"=>26,"code"=>"DKK","symbol"=>"Kr."],["id"=>27,"code"=>"BGN","symbol"=>"лв."],["id"=>28,"code"=>"THB","symbol"=>"฿"],["id"=>29,"code"=>"KWD","symbol"=>"KD, د.ك"],["id"=>30,"code"=>"MYR","symbol"=>"RM"],["id"=>31,"code"=>"PEN","symbol"=>"S/"],["id"=>33,"code"=>"PHP","symbol"=>"₱"],["id"=>34,"code"=>"IDR","symbol"=>"Rp"],["id"=>35,"code"=>"TWD","symbol"=>"NT$"]];?>
            <?php 
            
            
                 // ---------------------------------------------------------------------------------------------------
                 // Function to compare two jobs based on the published_at property
                 // function to sort the array $jobs by date    where this is the property $job->published_at
                  function compareByPublishedAt($a, $b) {
          
                     
                       $dateA = strtotime($a['published_at']);
                       $dateB = strtotime($b['published_at']);
                  return $dateA - $dateB;
                                 }

                 // Use usort to sort the jobs array using the compare function
                  usort($jobs, 'compareByPublishedAt');
                 // ---------------------------------------------------------------------------------------------------

               
               
                foreach ($jobs as $job):   //  I want to get the $jobs array sorted by date ( $job->published_at )  before to apply the foreach to show the rest of info
                
                    $currencyId = $job->salary_currency_id;
                    $matchingCurrency = array_filter($currencies, function ($currency) use ($currencyId) {
                        return $currency['id'] == $currencyId;
                    });
                    $selectedCurrency = reset($matchingCurrency);
            ?>

                <article class="job" data-job="<?Php echo $job->id; ?>">
                    <a href="<?php echo $this->job_url_builder(get_permalink(), 'job', $job->id); ?>">
                        <h4>
                            <?php echo $job->title; ?>
                        </h4>
                        <div class="job-meta">
                            <?php if ($render_settings['view_toggles']['location']): ?>
                                <span class="location">
                                    <?php echo !empty($job->macro_address) ? $job->macro_address : 'No Location'; ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($render_settings['view_toggles']['salary']): ?>
                                <span class="salary">
                                    <?php
                                    
                                     $originalValue = $job->salary;
                                     list($minPart, $maxPart) = explode(' - ', $originalValue);
                                     $min = filter_var($minPart, FILTER_SANITIZE_NUMBER_INT);
                                     $max = filter_var($maxPart, FILTER_SANITIZE_NUMBER_INT);
                                     $formattedRange = "$" . $min . "-" . $max . "k/year";
                                    
                                    echo !empty($formattedRange)
                                        ? $formattedRange
                                        : 'No Salary';
                                        
                                    //echo !empty($job->salary)
                                    //  ? $selectedCurrency['symbol'] . $job->salary
                                    //  : 'No Salary';  
                                    ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($render_settings['view_toggles']['job_type']): ?>
                                <span class="type">
                                    <?Php echo $job->job_type->name; ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </a>
                </article>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php if ($total_pages > 1): ?>
        <nav class="jobs-pagination">
            <?php if ($current_page > 1): ?>
                <a href="<?php echo $this->job_url_builder(get_permalink(), 'jobs_page', ($current_page - 1)); ?>">
                    <<< /a>
                    <?php endif; ?>
                    <?php $i = 1;
                    while ($i <= $total_pages): ?>
                        <a href="<?php echo $this->job_url_builder(get_permalink(), 'jobs_page', $i); ?>"
                            class="<?php echo (int) $current_page === $i ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php
                        $i++;
                    endwhile;
                    ?>
                    <?php if ($has_more_pages): ?>
                        <a
                            href="<?php echo $this->job_url_builder(get_permalink(), 'jobs_page', ($current_page + 1)); ?>">>></a>
                    <?php endif; ?>
        </nav>
    <?php endif; ?>
</section>

2

Answers


  1. function compareByPublishedAt($a, $b) {
       $dateA = strtotime($a['published_at']);
       $dateB = strtotime($b['published_at']);
    return $dateA - $dateB;
                                     }
    
    usort($jobs, 'compareByPublishedAt');
    

    you were pretty close !

    function compareByPublishedAt($a, $b) {
        $dateA = strtotime($a['published_at']);
        $dateB = strtotime($b['published_at']);
    
        if ($dateA == $dateB) {
            return 0;
        }
    
        return ($dateA < $dateB) ? -1 : 1;
    }
    

    Beside, as per your example, you pass $jobs and use it in the main code as an object (instead of an array). Be sure that the values published_at are at root level of the array.

    I’m pretty sure that you have a multi-dimensional array. Please update your question with it’s structure (just run print_r($jobs) and post here the output) so i can update this answer with the proper solution (unless you get it there first )

    Login or Signup to reply.
  2. Do yourself a service and update the function that generates the jobs, and add a property to the job call "ts" (or w/e). Make the value of that, the unix time of the published date.

    Now you can simply sort by $job->ts.

    For the current situation, just iterate the array (anyway you want), add the "ts" property to each, then just sort as normal.

    Keep it simple!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search