www.webdeveloper.com
Results 1 to 12 of 12

Thread: Php sort an array by date

  1. #1
    Join Date
    Nov 2014
    Posts
    5

    Php sort an array by date

    Hi Expert,
    please help solve this question

    (Link deleted -- MOD)

    thanks.
    Last edited by NogDog; 11-11-2014 at 08:10 AM.

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,637
    Please post your question here: linking to another forum is not cool.

    PS: Your answer will most likely utilize usort().
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Nov 2014
    Posts
    5
    have an issue to sort gallery photos by date. Right now its sort by Value (Name).*here is the code**index.php contains :*<div> <?php foreach($categories_array as $photo_category=>$photos_array){?> <?php $category_thumbnail = $gallery_url."/layout/pixel.gif"; if(file_exists('files/'.$photo_category.'/thumbnail.jpg')){ $category_thumbnail = $gallery_url.'/'.$photo_category.'/thumbnail.jpg'; } $category_url = $gallery_url.'/'.$photo_category; ?> <span class="category_thumbnail_span" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height+20;?>px;"> <a class="category_thumbnail_image" href="<?php echo $category_url;?>" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height;?>px; background-image:url('<?php echo $gallery_url;?>/layout/lens_48x48.png');" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <img src="<?php echo $category_thumbnail;?>" width="<?php echo $settings_thumbnail_width;?>" height="<?php echo $settings_thumbnail_height;?>" alt="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>" /> </a> <a class="category_thumbnail_title" href="<?php echo $category_url;?>" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>"> <?php echo htmlentities(str_replace('-',' ', truncate_by_letters($photo_category, 16, '..')), ENT_QUOTES, "UTF-8");?> (<?php echo count($photos_array);?>) </a> </span> <?php } ?> </div> the sort function :ksort($categories_array);

  4. #4
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    898
    Can you present your code in a more readable fashion? I'm sure you didn't format it like this intentionally.

  5. #5
    Join Date
    Nov 2014
    Posts
    5
    index.php contains :
    PHP Code:
    <div>

        <?php foreach($categories_array as $photo_category=>$photos_array){?>
        
            <?php 
            $category_thumbnail 
    $gallery_url."/layout/pixel.gif";
            if(
    file_exists('files/'.$photo_category.'/thumbnail.jpg')){
                
    $category_thumbnail $gallery_url.'/'.$photo_category.'/thumbnail.jpg';
            }
            
            
    $category_url $gallery_url.'/'.$photo_category;
            
    ?>
            
              <span class="category_thumbnail_span" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height+20;?>px;">
            <a class="category_thumbnail_image" href="<?php echo $category_url;?>" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height;?>px; background-image:url('<?php echo $gallery_url;?>/layout/lens_48x48.png');" title="<?php echo htmlentities(ucwords(str_replace('-'' '$photo_category)));?>">
            <img src="<?php echo $category_thumbnail;?>" width="<?php echo $settings_thumbnail_width;?>" height="<?php echo $settings_thumbnail_height;?>" alt="<?php echo htmlentities(ucwords(str_replace('-'' '$photo_category)));?>" />
            </a>
            <a class="category_thumbnail_title" href="<?php echo $category_url;?>" title="<?php echo htmlentities(ucwords(str_replace('-'' '$photo_category)));?>">
            <?php echo htmlentities(str_replace('-',' 'truncate_by_letters($photo_category16'..')), ENT_QUOTES"UTF-8");?> (<?php echo count($photos_array);?>)
            </a>
            </span>
        

        <?php ?>

    </div>



    PHP Code:
    $categories_array = array();

    $timer_1 microtime(true);
    // loop over files directory and read the categories
    if ($handle opendir('files')) {
        while (
    false !== ($folder readdir($handle))) {
            if(
    is_dir('files/'.$folder) and $folder!='.' and $folder!='..'){
                
                
    // define this key in the array, it will be blank, store categories as keys
                
    $categories_array[$folder] = array();

                
    // $total_photos_array[$folder] = 0;
                
                
    $files_in_dir scandir('files/'.$folder);
                foreach(
    $files_in_dir as $file){
                    
    // if file ends in _thumb.jpg
                    
    if(strpos($file'_thumb.jpg') === strlen($file)-10){
                        
    // $total_photos_array[$folder]++;
                        
    $base_file_name substr($file0,  strlen($file)-10);
                        
    // insert this file in the array of files
                        
    array_push($categories_array[$folder], $base_file_name);
                    }
                }
                
            }
        }
        
    closedir($handle);
    }
    $timer_2 microtime(true);

    ksort($categories_array); 

  6. #6
    Join Date
    Nov 2014
    Posts
    5
    i think i should fit these functions somwhere but no idea where exactly

    PHP Code:

    $files 
    = array();
    if (
    $handle opendir('.')) {
    while (
    false !== ($file readdir($handle))) {
           if (
    $file != "." && $file != "..") {
              
    $files[filemtime($file)] = $file;
           }
       }
       
    closedir($handle);


    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified end($files);

    foreach(
    $files as $file) {
        
    $lastModified date('F d Y, H:i:s',filemtime($file));
        if(
    strlen($file)-strpos($file,".swf")== 4){
            if (
    $file == $reallyLastModified) {
                
    // do stuff for the real last modified file
            
    }
            echo 
    "$file$lastModified";
        }


  7. #7
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    898
    Well, you presented the code cleaner but then you broke it into pieces and WE have no idea how they fit together and you didn't explain.

    How about isolating the problem in the code and just working with that?

  8. #8
    Join Date
    Nov 2014
    Posts
    5
    Quote Originally Posted by ginerjm View Post
    Well, you presented the code cleaner but then you broke it into pieces and WE have no idea how they fit together and you didn't explain.

    How about isolating the problem in the code and just working with that?
    The last code i took from internet. So not sure where to fit it.

  9. #9
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    898
    When you figure out how to write a concise program/script and can present something that makes sense to us here, then post it. You got some code from the internet? And you don't know where to put it?

    Sounds like you need to do some basic learning about what it means to be a computer programmer. This isn't like picking up a video game and running up a huge score 1 day after getting it. This is a science that takes knowledge, practice, reading, learning and experimentation to even begin. People actually go to college/school for this; others actually read books and learn by themselves. Do you think people make big salaries because they are 'not sure where to fit it'?

  10. #10
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,637
    Since the original question seemed to simply be how to sort an array by date, all we should need to know is what the array structure is, and how you want to sort it. For example:
    PHP Code:
    <?php

    $myArray 
    = array(
        array(
            
    'id' => 123,
            
    'date' => '2014-11-01'
        
    ),
        array(
            
    'id' => 12,
            
    'date' => '2014-19-31'
        
    ),
        array(
            
    'id' => 1234,
            
    'date' => '2014-11-03'
        
    ),
    );

    echo 
    "<pre>Starting array:\n".print_r($myArray,1)."</pre>";

    usort(
        
    $myArray,
        function(
    $a$b)
        {
            
    $da strtotime($a['date']);
            
    $db strtotime($b['date']);
            return 
    $da $db// use "<" to reverse sort
        
    }
    );

    echo 
    "<pre>Sorted array:\n".print_r($myArray,1)."</pre>";
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  11. #11
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,279
    A couple of problems there. The call back function should return -1, 0 or 1 and not true or false. And you'll increase performance by converting the date strings to time stamps, sorting and then converting the time stamps back to date strings.
    PHP Code:
     <?php
     
        date_default_timezone_set
    ('America/New_York');

        
    $my_array = array(
            array(
                
    'id' => 123,
                
    'date' => '2014-11-01'
                
    ),
            array(
                
    'id' => 12,
                
    'date' => '2014-12-31'
            
    ),
            array(
                
    'id' => 1234,
                
    'date' => '2014-11-03'
            
    ),
        );

        echo 
    "<pre>Starting array:\n".print_r($my_array,1)."</pre>";
        
        
    $my_array array_map (
            function (
    $r) {
                
    $r['date'] = strtotime($r['date']);
                return 
    $r;
            },
            
    $my_array
        
    );
        
        
    usort ($my_array,
            function (
    $a$b) {
                if (
    $a['date'] == $b['date']) {
                    return 
    0;
                } else {
                    return 
    $a['date'] < $b['date'] ? -1;
                }
            }
        );
            
        
    $my_array array_map (
            function (
    $r) {
                
    $r['date'] = date('Y-m-d'$r['date']);
                return 
    $r;
            },
            
    $my_array
        
    );

        echo 
    "<pre>Sorted array:\n".print_r($my_array,1)."</pre>";
    But with this example the date strings sort lexically so you can just use strcmp.
    PHP Code:
     <?php
     
        date_default_timezone_set
    ('America/New_York');

        
    $my_array = array(
            array(
                
    'id' => 123,
                
    'date' => '2014-11-01'
                
    ),
            array(
                
    'id' => 12,
                
    'date' => '2014-12-31'
            
    ),
            array(
                
    'id' => 1234,
                
    'date' => '2014-11-03'
            
    ),
        );

        echo 
    "<pre>Starting array:\n".print_r($my_array,1)."</pre>";
        
        
    usort ($my_array,
            function (
    $a$b) {
                return 
    strcmp($a['date'], $b['date']);
            }
        );

        echo 
    "<pre>Sorted array:\n".print_r($my_array,1)."</pre>";
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  12. #12
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,637
    Quote Originally Posted by Charles View Post
    ...But with this example the date strings sort lexically so you can just use strcmp....
    Well, yes, if you can guarantee the date will always be in that format, which in this case just happened to be what I typed in, copied and pasted and edited a couple times. And you could put the whole thing into a function (or method), with error-checking, etc., etc. -- but ultimately we're underscoring the importance of defining the functional requirements before trying to develop a specific solution.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles