1

I have an array $post of the following format

$post[0] = [
    'id'    => '103',
    'date'  => '2016-04-17 16:30:12',
    'desc'  => 'content description'
];

$post[1] = [
    'id'    => '102',
    'date'  => '2016-04-17 12:30:12',
    'desc'  => 'content description'
];

$post[2] = [
    'id'    => '101',
    'date'  => '2016-04-17 10:30:12',
    'desc'  => 'content description'
];

$post[3] = [
    'id'    => '100',
    'date'  => '2016-04-16 08:30:12',
    'desc'  => 'content description'
];

I would like to use strtotime(date) from the $post as an unique array key, and create:

$summary['day-of-2016-04-17'] = [
    'counts' => '3'
];

$summary['day-of-2016-04-16'] = [
    'counts' => '1' 
];

Where counts is the number of occurrence of the date used as the key.

I only need to keep the date itself as the unique key and time value is irrelevant.

I'll need the key value to be unix timestamp for further processing.

How can I implement this in the most efficient way?

0

1 Answer 1

1

Just use the date as key. The simplest way would be just use explode the date time, get the first fragment (which is the date), and assign it just like any normal array:

$summary = [];
foreach($post as $value) {
    $dt = explode(' ', $value['date']); // break the date
    $day_of = "day-of-{$dt[0]}"; // create the naming key
    if(!isset($summary[$day_of])) { // initialize
        $summary[$day_of]['counts'] = 0;
    }
    $summary[$day_of]['counts']++; // increment
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.