Shijin TR
Shijin TR

Reputation: 7768

Create date array from two dimensional array in PHP

I have an array like,

 $my_array=array(array('month'=> 3,
                       'day'=> 4,
                       'hour' => 1,
                       'minut' => 15,
                       'year'=> 2014),
                    array('month'=> 5,
                       'day'=> 7,
                       'hour' => 1,
                       'minut' => 50,
                       'year'=> 2012)
                       ----------
                        );

I want to create a new array from this array like,

$new_array=array('2014-3-4 1:15','2012-5-7 1:50');

I know it is possible with traversing each element with a loop,Is there any easy way?.because my array contain large number(more than 50000) of data.

Upvotes: 3

Views: 105

Answers (3)

Alma Do
Alma Do

Reputation: 37365

You may use array_map(), but, please, note: this will use loop internally.

$result = array_map(function($x)
{
   return $x['year'].'-'
         .$x['month'].'-'
         .$x['day'].' '
         .$x['hour'].':'
         .$x['minut'];
}, $my_array);

So, this won't increase overall performance. Also it won't check your dates. I recommend to use mktime() and date() so you'll be able to result in any date format. Or may be use checkdate() if you'll need to check if element contains valid date (btw, good alternative to those functions is DateTime API)

The only good thing about plain concatenation is that is will be a little bit faster (because in case of using date functions there will be overhead, obviously).

Upvotes: 1

Realitätsverlust
Realitätsverlust

Reputation: 3953

Ofc its possible:

foreach($my_array as $k => $v) {
    $new_array[i] = $v["year"]."-".$v["month"]."-".$v["day"]." ".$v["hour"].$v["minut"];
    i++;
}

//Untested

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Try something like this using array_map:

$newArr = array_map(function($d) {
    return $d['year'] . '-' . $d['month'] . '-' . $d['day'] . ' ' . $d['hour'] . ':' . $d['minut'];
}, $my_array);

Upvotes: 2

Related Questions