Php 从文件读入关联数组
我必须创建一个页面,用户可以在其中搜索郊区,该页面将打印该郊区的邮政编码 在将Php 从文件读入关联数组,php,arrays,associative-array,Php,Arrays,Associative Array,我必须创建一个页面,用户可以在其中搜索郊区,该页面将打印该郊区的邮政编码 在将.txt文档中的数据放入关联数组的变量时,我遇到了一些困难 谢谢你的帮助 这就是我目前所拥有的 <?php $file = "postcode.txt"; $handle = fopen($file, 'r'); $postcodearray = file($file); $suburb = explode(",", ); $postcodearray[$sub
.txt
文档中的数据放入关联数组的变量时,我遇到了一些困难
谢谢你的帮助
这就是我目前所拥有的
<?php
$file = "postcode.txt";
$handle = fopen($file, 'r');
$postcodearray = file($file);
$suburb = explode(",", );
$postcodearray[$suburb] = $postcode;
fclose($handle)
?>
等。在处理文件时,我更喜欢
文件\u获取\u内容
<?php
$content = file_get_contents('postcode.txt');
$rows = explode("\n", $content);
$data = [];
foreach ($rows as $row) {
$columns = explode(',', $row);
$data[$columns[0]] = $columns[1];
}
另一种阵列将墨尔本东部和西部组合成一个带有子阵列的阵列。(看输出,我不知道如何解释)
我在空间上爆炸墨尔本东部,并使用东部作为阵列中的一个键
// 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);
输出:
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"
}
}
}
$postcodearray
看起来像什么?
// 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);
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"
}
}
}