1

I have a very large txt file javascript array - too big for me to go and edit each entry separately. It looks like this:

["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265], &c.

How can I pass this file through PHP to change all the dates and write a new file? I'm thinking I need to use strptime() or strtotime() but I'm not sure how to proceed.

The date format is Month/Day/Year.

EDIT: I ended up recreating the array from a CSV file. Here's the code I used in case anyone's interested. Thanks for the help.

$handle = fopen("stuff.csv", "r");

while(($data = fgetcsv($handle, ",")) !== FALSE) {
    echo "[" . strtotime($data[0]) . ", " . $data[1] . "],<br />";
}
Sam Nabi
  • 379
  • 3
  • 14

2 Answers2

2

Match all the dates in the string with a regular expression, then use strtotime() on the results:

$str = '["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]';
$p = '#(\d+/\d+/\d{4}\s\d{2}:\d{2})#';
preg_match_all($p, $str, $matches);

foreach ($matches[1] as $m) {
  echo strtotime($m) . "\n";
}

UPDATE: Just realized you said your data is in a javascript array. You can handle this easily in JS as well:

var new_times = [];
var times = [["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]];

for(i=0; i < times.length; i++) {
  var d = new Date(times[i][0]);
  var new_arr = [(d.getTime() / 1000), times[i][1]];
  new_times.push(new_arr);
}
  • @Sam Nabi I just realized you have it in a javascript array ... are you passing it to php in a JSON string? –  Dec 16 '11 at 22:25
  • Thanks! This'll get me going. Do PHP strings have a size limit? My file has millions of characters. – Sam Nabi Dec 16 '11 at 22:29
  • I'm just including it in a php file. It's not being converted to JSON. – Sam Nabi Dec 16 '11 at 22:30
  • The size limit is your machine's memory. If your data is in a csv file you might be better served processing it with [`fgetcsv()`](http://us2.php.net/manual/en/function.fgetcsv.php) ... you might also take a look at [this SO post on reading large files in PHP](http://stackoverflow.com/questions/162176/reading-very-large-files-in-php) –  Dec 16 '11 at 22:35
0

JavasScript

var times = [["12/1/2011 00:00",15848],["12/1/2011 01:00",15108],["12/1/2011 02:00",14643],["12/1/2011 03:00",14265]];
//var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
for(i in times) {
    var time = times[i][0].split(/\/|\s|:/i);
    console.log(time);
    date = new Date(time[2], time[0], time[1], time[3], time[4]);
    console.log(date.getTime());
}
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130