3

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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

Ofc its possible:

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

//Untested

2 Comments

I know this method.But my array is too large.it will timeout before foreach
de1.php.net/set_time_limit should do it. Dont forget to give the user feedback that the script is still working.
1

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).

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.