从文件读取到关联数组

I have to create a page, where the user is able to search a suburb and the page will print the postcode of that suburb.

I am having a little difficulty with putting the data from the .txt document into the variables for the associative array.

Thanks for your help.

This is what I have so far.

    <?php

    $file = "postcode.txt";
    $handle = fopen($file, 'r');
    $postcodearray = file($file);

    $suburb = explode(",", );
    $postcodearray[$suburb] = $postcode;

    fclose($handle)
    ?>

and this is the format of the .txt document...

3000,MELBOURNE  
3001,MELBOURNE  
3002,EAST MELBOURNE  
3003,WEST MELBOURNE  

etc.

I prefer file_get_contents when working with files

<?php

$content = file_get_contents('postcode.txt');

$rows = explode("
", $content);

$data = [];
foreach ($rows as $row) {
    $columns = explode(',', $row);

    $data[$columns[0]] = $columns[1];
}
$postcodearray = file($file);

foreach($postcodearray as $pca){
    $p_codes=explode(',',$pca);
    $postcodearray2[$p_codes[1]] = $p_codes[0];
}
print_r($postcodearray2); 

An alternative array would group MELBOURNE EAST and WEST in one array with subarrays. (Look at the output, I don't know how to explain it)

I explode MELBOURNE EAST on space and use EAST as a key in the array.

// Replace this line with file_get_contents("postcode.txt");
$txt = "3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
3603,WEST SYDNEY
3103,NORTH PERTH";

$rows = explode(PHP_EOL, $txt);
$arr= [];

foreach($rows as $row){
   List($postcode, $suburb) = explode(",", $row);
   If(in_array(substr($suburb,0,4), array("EAST", "WEST")) ||  in_array(substr($suburb,0,5), array("SOUTH", "NORTH"))){
        // If the suburb includes a direction explode it to temp.
        $temp = explode(" ", $suburb);
        $arr[$temp[1]][$temp[0]][] = $postcode;
    }else{
        // If there is no direction just save it as suburb "main"
        $arr[$suburb][] = $postcode;
    }

}

Var_dump($arr);

https://3v4l.org/RXgSR

Output:

array(3) {
  ["MELBOURNE"]=>
   array(4) {
    [0]=>
    string(4) "3000"
   [1]=>
    string(4) "3001"
     ["EAST"]=>
    array(1) {
      [0]=>
       string(4) "3002"
    }
    ["WEST"]=>
    array(1) {
     [0]=>
      string(4) "3003"
    }
  }
  ["SYDNEY"]=>
   array(1) {
    ["WEST"]=>
    array(1) {
      [0]=>
       string(4) "3603"
     }
  }
  ["PERTH"]=>
  array(1) {
    ["NORTH"]=>
    array(1) {
      [0]=>
      string(4) "3103"
        }
  }
}