php数组:返回匹配元素

时间:2011-04-25 21:00:50

标签: php arrays

 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));
}

}

我希望我的类中的另一个函数返回一些具有特定日期的数组。使用exif_read_data函数从照片中提取日期。他们看起来有点谎言:2011:04:01 16:12:23。我正在寻找的功能应该返回特定日期的所有照片。所以我想知道我如何使函数返回,例如,所有带有日期戳的照片看起来像2011:04:01 xx:xx:xx。希望你明白我的意思。提前谢谢!

3 个答案:

答案 0 :(得分:1)

这应该这样做:

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');

您可能还想查看array_filter()功能。


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;
}

答案 1 :(得分:0)

function get_by_date($date) {
    $date = strftime('%D', strtotime($date));
    $photos = array();
    foreach($this->photos as $photo) {
        if(strftime('%D', strtotime($photo['date'])) == $date) {
            $photos[] = $photo;
        }
    }
    return $photos;
}

答案 2 :(得分:0)

我只是检查前10个字符是否相同:

public function getByDate($date) {
    $return = array();
    foreach ($this->photos as $photo) {
        if ($date == substr($photo['date'], 0, 10)) {
            $return[] = $photo;
        }
    }

    return $return;
}

如果您使用的是PHP 5.3,则可以使用array_filter和关闭:

执行此操作
public function getByDate($date) {
    return array_filter($this->photos, function($photo) use($date) {
        return $date == substr($photo['date'], 0, 10);
    });
}
相关问题