I have a file like below, which I need to convert into an array:
ABCLine, Number, One DEFNumber, Two, Line GHIThree, Line, Number
I can get each line and turn it into a value of an array, but what I need to do is take the first 3 characters and turn that into a key and then the rest of the line into the value.
So my expected array would be:
Keys | Values
----------------------------
ABC | Line, Number, One
DEF | Number, Two, Line
GHI | Three, Line, Number
I honestly am not too sure where to begin, I've been looking all over and haven't been able to find a way to just take those first 3 characters and turn those into a key for the remainder of the line.
I started with some code, which looks like this:
<?php
echo "Name<br/>";
$file = "hw3.txt";
$f1 = fopen($file, 'r');
$array = array();
?>
This should work for you:
Get your file into an array with file()
. Then walk through your array with array_walk()
and take the first 3 characters of each value and add it to the $keys
array. After that you can remove the first 3 characters from the value.
At the end just array_combine()
your $keys
array with $arr
, e.g.
<?php
$arr = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$keys = [];
array_walk($arr, function(&$v, $k)use(&$keys){
$keys[] = substr($v, 0, 3);
$v = substr($v, 3);
});
$arr = array_combine($keys, $arr);
print_r($arr);
?>
output:
Array
(
[ABC] => Line, Number, One
[DEF] => Number, Two, Line
[GHI] => Three, Line, Number
)
You could extract the first 3 characters with the substr function, and use it as the key of your array, then store rest of the string as another array, for example:
$file = "hw3.txt";
$f1 = fopen($file, 'r');
$array = array();
while (($line = fgets($f1)) !== false) {
$key = substr($line, 0, 3);
$val = substr($line, 3);
$array[$key] = $val;
}