MuntingInsekto
MuntingInsekto

Reputation: 1593

PHP Array Contain string

i create a method that will read a file with the application/octet type and here are some of the code. Raw data :

GTHHS;MEKID Interface;5496;2012-07-20; NM1;081;IN1;980898989;2001-01-15;Mr;Gaf;Uhkil;Uhkil,Gaf;PRI;Gaf

 $contents = file_get_contents($tmp_filename);
 $stringContents = explode(";", $contents); 

Now it gives me this output :

Array
(
    [0] => GTHHS
    [1] => MEKID Interface
    [2] => 5496
    [3] => 2012-07-20
NM1
    [4] => 081
    [5] => IN1
    [6] => 980898989
    [7] => 2001-01-15
    [8] => Mr
    [9] => Gaf
    [10] => Uhkil
    [11] => Uhkil,Gaf
    [12] => PRI
    [13] => Gaf
PR1
    [14] => 081
    [15] => IN1
    [16] => 20730089
    [17] => 7 The Schooner
    [18] => Auhaas
    [19] => Huuula Ave
    [20] =>  
    [21] => Kishma
PR2
    [22] => 081
    [23] => IN1
    [24] => 232323233
    [25] => 400006
    [26] => HGD
    [27] => M
    [28] => M
    [29] => 2007-10-16
    [30] => 1976-03-31
);

How can i make the NM1, PR1 as the head of array like this :

Array (
     [NM1] = array(
            [0] => GTHHS 
            [1] => MEKID Interface 
            [2] => 5496 
            [3] => 2012-07-20
            )
);

I am planning also to make the inner array [0]-[3] as json.

Upvotes: 0

Views: 101

Answers (1)

ToBe
ToBe

Reputation: 2681

If you explode the contents by \n you have each line starting with that identifier. If you then just explode by ; in that line and add it as a sub array, you got it like you want.

This actually looks like a plain old CSV file with your ifentifier in line one. If so, try something like this:

$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE)
    {
        $key = array_shift($row);
        $data[$key] = $row;
    }
    fclose($handle);
}

echo json_encode($data);

http://php.net/manual/en/function.str-getcsv.php

Upvotes: 1

Related Questions