bsh
bsh

Reputation: 447

Convert data to associated array php

Is it possible in php to convert this kind of data

    ABANO TERME A001
ABBADIA CERRETO A004
ABBADIA LARIANA A005
ABBADIA SAN SALVATORE   A006
ABBASANTA   A007
ABBATEGGIO  A008
ABBIATEGRASSO   A010

to an associated array where in the first column are keys and in the second column are values?

Upvotes: 1

Views: 79

Answers (3)

Gaurav
Gaurav

Reputation: 721

$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
    $line_arr = explode(" ", $filesop);
    $value = end($line_arr);
    unset($line_arr[array_search($value, $line_arr)]);
    $key = implode(" ", $line_arr);
    $result_arr[trim($key] = trim($value);
}
print_r($result_arr);

Store in the text file like this (separated by commas):

ABANO TERME,A001
ABBADIA CERRETO,A004
ABBADIA LARIANA,A005
ABBADIA SAN SALVATORE,A006
ABBASANTA,A007
ABBATEGGIO,A008
ABBIATEGRASSO,A010

Solution to read file:

$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
    $line_arr = explode(",", $filesop);
    $value = end($line_arr);
    unset($line_arr[array_search($value, $line_arr)]);
    $key = implode(",", $line_arr);
    $result_arr[trim($key] = trim($value);
}
print_r($result_arr);

Upvotes: 2

Deus777
Deus777

Reputation: 1836

One solution for this particular data would be:

<?php

$data = file_get_contents('data.txt')

//use regular expressions to parse whole file at once
preg_match_all("/([^\s]+\s?[^\s]+?)\s+(.\d+)$/m", $data, $m);

//and combine results from result array ($m)
//first entry - $m[0] contains whole lines thats why I dont use it here
//second entry - $m[1] - data from first brackets is an array key
//third entry - $m[2] - is a value (both are separated by some number of spaces - \s+)
$array = array_combine($m[1], $m[2]);

print_r($array);

?>

output:

Array
(
    [ABETONE] => A012
    [ABRIOLA] => A013
    [ACATE] => A014
    [ACCADIA] => A015
)

of course, as colleagues above pointed out, this depends on where data came from, and if this particular set is representative.

Upvotes: 1

Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4038

    $txt = file_get_contents('foo.txt');
    $arr=array_values(array_filter(explode(' ',$txt)));
    $new=[];
    for($i=0; $i<count($arr)-1;$i++){

    $new[$arr[$i]]=$arr[++$i];
    }

    print_r($new);

Upvotes: 2

Related Questions