phpmultidimensional-arrayexplode

PHP explode text to multidimensional array


I want to 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?


Solution

  • 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);