Чтение из файла в ассоциативный массив

Я должен создать страницу, где пользователь может искать пригород, и страница напечатает почтовый индекс этого пригорода.

У меня возникли небольшие трудности с размещением данных из .txt документ в переменные для ассоциативного массива.

Спасибо за вашу помощь.

Это то, что я до сих пор.

    <?php

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

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

fclose($handle)
?>

и это формат документа .txt …

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

и т.п.

-3

Решение

$postcodearray = file($file);

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

Другие решения

я предпочитаю file_get_contents при работе с файлами

<?php

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

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

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

$data[$columns[0]] = $columns[1];
}
0

Альтернативный массив сгруппировал бы MELBOURNE EAST и WEST в один массив с подмассивами. (Посмотрите на вывод, я не знаю, как это объяснить)

Я взрываю МЕЛЬБУРН ВОСТОК в космосе и использую ВОСТОК в качестве ключа в массиве.

// 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

Выход:

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"}
}
}
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector