从文件读取到关联数组

时间:2017-09-01 07:39:09

标签: php arrays associative-array

我必须创建一个页面,用户可以在该页面中搜索郊区,页面将打印该郊区的邮政编码。

.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 个答案:

答案 0 :(得分:1)

$postcodearray = file($file);

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

答案 1 :(得分:0)

我在使用文件时更喜欢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];
}

答案 2 :(得分:0)

另一个数组会将MELBOURNE EAST和WEST分组到一个带有子阵列的数组中。 (看输出,我不知道如何解释)

我在太空中爆炸MELBOURNE EAST并使用EAST作为数组中的键。

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