-2

So I am new to php and I am writing a script to take a time stamp in the form of "January 23, 2014 at 11:01PM" and break it into a multi-dimensional array with elements for month, date, year, hour, and minutes. Here is my code:

$raw_data= array("January 20, 1993 at 10:20PM", "September 6, 1991 at 6:23PM");
        var_dump($raw_data);
        $num_dates= count($raw_data);

//Step 1: break content into month, day, year, hour, and minutes
    for ($i=0; $i=($num_dates-1); $i++) {   
        $partial_data = implode(preg_split("/[A-Z]{2}/", $raw_data[$i]));
        $broken_data[$i] = preg_split("/[\s,:]/", $partial_data);
        unset($broken_data[$i][2]);
        unset($broken_data[$i][3]);
}

For some reason, when I run this in the terminal it seems to be an infinite loop. I tested the code inside the for-loop on a one-dimensional array, and the output was what I expected, so I am pretty sure my problem is because I don't know how to format a for loop in php. Does anyone see an obvious beginner mistake?

4 Answers 4

1

Because of this: $i=($num_dates-1) You need to check the condition ==, not use an assignment =. Although in this case it appears you want to do something like this: $i <= ($num_dates-1). You may have just forgot to type <.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I did forget the <. Thank!
1

This is assigning a value...

$i=($num_dates-1);

This is comparison and what you need:

$i < $num_dates

Comments

1

Not directly answering your question, but there's easier ways to parse the date. You can use strtotime() to go from string to timestamp, then create a DateTime to access date parts using DateTime::format().

http://php.net/manual/en/function.strtotime.php

http://php.net/manual/en/class.datetime.php

http://php.net/manual/en/datetime.format.php

Comments

0
$broken_data = array();
$raw_data = array("January 20, 1993 at 10:20PM", "September 6, 1991 at 6:23PM");

foreach($raw_data as $date) { 
   if ($d = strtotime(str_replace(' at ', ', ', $date)))  
     $broken_data[] = array(
        date('F', $d), date('j', $d), date('Y', $d), date('G', $d), date('i', $d)
     );
}

var_dump($broken_data);

If the years are above 1901 and below 2038.

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.