Q:

Loop through lines in text file, search for delimiter and add to associative array

I have some text as such: 
     $string = “———version1———
                item1-result1
                item2-result2
                item3-result3
                ———version2———
                Item1-result4
                Item2-result5
                Item3-result6
                ———version3———
                Item1-result7
                Item2-result8
                Item3-result9”

I need to loop through the lines and explode the lines that contain the hyphen delimiter (-) and add to an associative array but group by version, so the values would map to each other like so:
The desired result I need is something like: 
   array = [
    Version1_item1 => result1,
    Version1_item2=>result2
    …
    …
    Version2_item1=>result4
    etc
    ]

I could use explode, and the add the item values to one array and the results to another and then use array_combine but I can't seem to get the code right.
 $final_result = array();
foreach (explode('\n', $string) as $piece) {
    $result = array();
    $result[] = explode('-', $piece);

Can anyone help? 

A:

The main issue is that you are using '\n' but, into single quotes, it doesn't represent a newline. You should use "\n", into double quotes. 
You should use trim() to remove extra spaces before and after the text on each line. 
Finally, you are appending to $result the array of your explode, instead of assign to it:
$string = "This is the text file
        item1-result1
        item2-result2
        item3-result3
        End of text file";

$final_result = array();
foreach (explode("\n", $string) as $piece) {
    $piece = trim($piece);
    $result = explode('-', $piece);
    if (count($result) == 2) {
        $final_result[ $result[0] ] = $result[1];
    }
}
print_r($final_result);

Outputs:
Array
(
    [item1] => result1
    [item2] => result2
    [item3] => result3
)

EDIT
$string = "———version1———
           item1-result1
           item2-result2
           item3-result3
           ———version2———
           Item1-result4
           Item2-result5
           Item3-result6
           ———version3———
           Item1-result7
           Item2-result8
           Item3-result9";

$final_result = array();
$current_version = '';
foreach (explode("\n", $string) as $piece) {
    $piece = trim($piece);
    if (strpos($piece, '———') === 0) $current_version = trim($piece,'—');
    $result = explode('-', $piece);
    if (count($result) == 2) {
        $final_result[ $current_version . '_' . $result[0] ] = $result[1];
    }
}
print_r($final_result);

Outputs:
Array
(
    [version1_item1] => result1
    [version1_item2] => result2
    [version1_item3] => result3
    [version2_Item1] => result4
    [version2_Item2] => result5
    [version2_Item3] => result6
    [version3_Item1] => result7
    [version3_Item2] => result8
    [version3_Item3] => result9
)

