如何使用PHP正确解析.ini文件

I am parsing .ini file which looks like this (structure is same just much longer)

It is always 3 lines for one vehicle. Each lines have left site and right site. While left site is always same right site is changing.

00code42=52
00name42=Q7 03/06-05/12 (4L) [V] [S] [3D] [IRE] [52]
00type42=Car
00code43=5F
00name43=Q7 od 06/12 (4L) [V] [S] [3D] [5F]
00type43=Car

What I am doing with it is:

$ini = parse_ini_file('files/models.ini', false, INI_SCANNER_RAW);
foreach($ini as $code => $name)
{
   //some code here
}   

Each value for each car is somehow important for me and I can get to each it but really specifily and I need your help to find correct logic.

What I need to get:

  • mCode (from first car it is 00)
  • code (from first car it is 52)
  • vehicle (from first car it is Q7 03/06-05/12 (4L))
  • values from [] (for first car it is V, S, 3D, IRE , 52
  • vehicle type ( for first car it is "car")

How I get code from right site:

$mcode = substr($code, 0, 2);  //$code comes from foreach
echo "MCode:".$mcode;   

How I get vehicle type:

echo $name; // $name from foreach

How I parse values like vehicle and values from brackets:

    $arr = preg_split('/\h*[][]/', $name, -1, PREG_SPLIT_NO_EMPTY); // $name comes from foreach
array(6) { [0]=> string(19) "Q7 03/06-05/12 (4L)" [1]=> string(1) "V" [2]=> string(1) "S" [3]=> string(2) "3D" [4]=> string(3) "IRE" [5]=> string(2) "52" } 

So basicly I can get to each value I need just not sure how to write logic for work with it.

  • In general I can skip the first line of each car because all values from there is in another lines as well
  • I need just 2th and 3th line but how can I skip lines like this? (was thinking to do something like :

    if($number % 3 == 0) but I dont know how number of lines.

  • After I get all data I cant just echo it somewhere but I also need to store it in DB so how can I do this if

I will really appriciate your help to find me correct way how to get this data in right cycle and then call function to insert them all to DB.

EDIT: I was thinking about something like: http://pastebin.com/C97cx6s0 But this is just structure which not working

If your data is consistent, use array_chunk, array_keys, and array_values

foreach(array_chunk($ini, 3, true) as $data) 
{
    // $data is an array of just the 3 that are related
    $mcode = substr(array_keys($data)[0], 0, 2);
    $nameLine = array_values($data)[1];
    $typeLine = array_values($data)[2];

    //.. parse the name and type lines here.

    //.. add to DB
}