Delimited txt into an array with keys provided by first cell of delimieted txt [duplicate]

44
October 11, 2018, at 4:10 PM

This question is an exact duplicate of:

  • fopen not displaying contents 1 answer
ID  OID Title   Description Option  Price
01  01JAP   Japanese Model  Japanese Model of the Dave Smith    Japanese    "$3,000 "
02  02ENG   English Model   English Model of the dave Smith     english "$1,000 "

The txt file, example shown above is delimited with /t.

I need the first line to become the keys of my array, so the ID or OID for example

"01" => array(
"ID" => "01",
"OID" => "01JAP",
"title" => "Japaneses model",
"description" => "Japanese Model of the Dave Smith ",
"option" => "Japanese",
"price" => 3000

),

I've read and tried to use explode() but was also looking at fgetcsv(), but haven't found any examples putting it into an array with keys provided by the delimited txt file.

any help would be greatly appreciated!

Answer 1

To use the first line as the data keys, you need to read the line into a separate array and then on each line you read use array_combine() to add the keys to the values...

$fh = fopen("file.txt", "r");
$headers = fgetcsv($fh, 0, "\t");
$data = [];
while ( $row = fgetcsv ($fh, 0, "\t" ) ) {
    $data[] = array_combine($headers, $row);
}
fclose($fh);

This assumes the file is tab delimited, change the "\t" if you need another delimiter.

Answer 2

You can try an explode on tabulation or spaces like :

explode("\t", $your_data)

You can tout parse with a regexp like :

preg_match_all("/([^\t])/", $your_data, $matches)

Get your data by simply :

$your_data = file_get_contents('your/file');
READ ALSO
Php mysql insert/update from json

Php mysql insert/update from json

hello i have a problem insert data to mysql working but i need if not exist data create if exist update all rowNow after each refresh page add same data but not updating

9
$_POST is empty in push notification response (PHP)

$_POST is empty in push notification response (PHP)

Can anybody tell me how to get the response data from a push notification responseI am currently only able to get data from headers, but $_POST is an empty array

25
Email Open Rate Tracker - Differences in email client

Email Open Rate Tracker - Differences in email client

I've implemented a very common approach to email open rate tracking using a 1x1px transparent image:

33
Redirect route to language prefix in Symfony 4

Redirect route to language prefix in Symfony 4

Since version 41, Symfony now handles multilingual routing without the need of an external plugin (https://symfony

22