doudang4568 2011-04-25 21:00
浏览 43
已采纳

php数组:返回匹配元素

 class Photos 
{
private $photos = array();

function add_photo($filename, $date, $lat, $long) 
{
  $this->photos[] = array('filename' => $filename, 'date' => $date, 'lat' => $lat,  'long' => $long);
    return $this;
}

function get_all() 
{
   return json_encode($this->photos);
}

function get_N($n) 
{
    return json_encode(array_slice($this->photos, 0, $n));
}

}

I would like another function in my class that returns some of the arrays with a certain date. The date is extracted from photos using the exif_read_data function. They look something liek this: 2011:04:01 16:12:23. The function that im looking for should return all the photos from a certain date. So i would like to know how i make the function return, for example, all photos with a datestamp looking like 2011:04:01 xx:xx:xx. Hope you understand what i mean. Thanks in advance!

  • 写回答

3条回答 默认 最新

  • douchui1657 2011-04-25 21:07
    关注

    This should do it:

    class Photos 
    {
        private $photos = array();
    
        function add_photo($filename, $date, $lat, $long) { /* ... */ }
    
        function get_all() { /* ... */ }
    
        function get_N($n) { /* ... */ }
    
        function get_by_date($date)
        {
            $result = array();
    
            foreach ($this->photos as $photo)
            {
                if (strpos($photo['date'], $date) === 0)
                {
                    $result[] = $photo;
                }
            }
    
            return $result;
        }
    }
    
    Photos::get_by_date('2011:04:01');
    

    You may also want to look at the array_filter() function.


    function get_all_dates()
    {
        $result = array();
    
        foreach ($this->photos as $photo)
        {
            $result[substr($photo['date'], 0, 10)] = null;
        }
    
        return array_keys($result);
    }
    

    function get_all_dates_with_count()
    {
        $result = array();
    
        foreach ($this->photos as $photo)
        {
            $date = substr($photo['date'], 0, 10);
    
            if (empty($result[$date]))
            {
                $result[$date] = 0;
            }
    
            ++$result[$date];
        }
    
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 数学建模数学建模需要
  • ¥15 c语言数据结构实验单链表的删除
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决