I wanna explode this text to three dimensional array:

Q 11 21 21 ( 40 44 23 ! 24 ! ! Q ! 32 22 48 18 23 49 ! ! ! ! 24 23 Q ! 19 23 06 49 29 15 22 ! ! ! Q ! 20 ( 23 23 ( 40 ! ! ! ! Q ! 21 06 ! 22 22 22 02 ! ! !


Q ! ( 40 05 33 ! 05 ! ! ! ! Q ! 49 49 05 20 20 49 ! ! ! Q ! ! 05 34 ( 40 ( ( 1 Q ! ! 46 46 46 46 46 46 ! ! ! Q ( 46 07 20 12 05 33 ! ! ! !

This is timetable is in text form. The following are the conditions that determine each value in the array:

  1. new row = next time table;
  2. Q = new day;
  3. space = next hour
  4. ! = free hour,
  5. ( = duplicit hour

And I want it like this: array[timetable][day][hour]

How can I do that? Is there choice do it by PHP explode function?

share|improve this question
2  
Satisfy my own curiosity: is that format part of a standard? – Mike B Sep 27 '11 at 20:38
2  
you will have to explain better to get any answers.. – amosrivera Sep 27 '11 at 20:39
What prevents you from just coding the parser for that? I mean you already formulated the format, what prevents you to continue? – hakre Sep 27 '11 at 20:48

3 Answers

up vote 0 down vote accepted

Without really understanding how your strings work; This code should do the job.

$timetables = explode("\n", $source);

foreach($timetables as $tablekey => $days)
{
    $timetables[$tablekey] = explode('Q', $days);

    foreach($timetables[$tablekey] as $daykey => $hours)
        $timetables[$tablekey][$daykey] = explode(' ', $hours)
}

print_r($timetables, true);
share|improve this answer

What a nice format! I think I still don't get it, but I'll try answering anyway...

  1. use explode with "\n" and you'll get an array of timetables
  2. for each element of this array, replace it with an explode of itself with 'Q' and you'll have a 2-dimensional array
  3. for each element of each element of this array, replace the element with an explode of itself with ' '

Try to do this and if you're having trouble, edit your question with the code you'd come up with.

share|improve this answer
$x = //...
$x = explode("\n", $x);
foreach($x as $k => $v) {
  $x[$k] = explode("Q", $x[$k]);
  foreach($x[$k] as $kk => $vv) {
    $x[$k][$kk] = explode(" ", $x[$k][$kk]);
  }
}

With array_map I think you wiil get somewhat nicer code.

share|improve this answer
1  
Semantic code gets you a better upgrade tbh. – sg3s Sep 27 '11 at 21:00

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.