我有一个像这样的数组..
array(26053) {
[0]=>
array(1) {
["New York"]=>
array(10) {
["state"]=>
string(8) "New York"
["state_code"]=>
string(0) ""
["country_code"]=>
string(1) "1"
["country"]=>
string(24) "United States Of America"
["lat"]=>
string(0) ""
["long"]=>
string(0) ""
["city_id"]=>
string(5) "70834"
["country_id"]=>
string(4) "6532"
["country_iso"]=>
string(2) "US"
["orignal_name"]=>
string(1) ""
}
}
[1]=>
array(1) {
["Mexico, Ciudad De"]=>
array(10) {
["state"]=>
string(0) ""
["state_code"]=>
string(0) ""
["country_code"]=>
string(2) "52"
["country"]=>
string(6) "Mexico"
["lat"]=>
string(0) ""
["long"]=>
string(0) ""
["city_id"]=>
string(5) "72329"
["country_id"]=>
string(0) ""
["country_iso"]=>
string(2) "MX"
["orignal_name"]=>
string(1) ""
}...
同样聪明
为了创建上面的数组,我做了这个
$filename="city.dat";
$lines=file($filename);
$city_array = array();
foreach ($lines as $line_num => $value) {
$tmp_arry = array();
$parts = explode("\t", $value);
$tmp_arry[$parts[0]] = array();
$tmp_arry[$parts[0]]['state'] = $parts[1];
$tmp_arry[$parts[0]]['orignal_name'] = $parts[11];
array_push($city_array, $tmp_arry);
}
有什么办法可以让它达到以下格式,因为我会更容易搜索这种格式,因为city.data文件中的数据很大
array(26053){
["New York"]=>.......
["Mexico"] => ...... }
感谢您的帮助
答案 0 :(得分:0)
是的,你可以完全这样做(只要城市名称为valid keys)
$filename="city.dat";
$lines=file($filename);
$city_array = array();
foreach ($lines as $line_num => $value) {
$parts = explode("\t", $value);
$city_array[$parts[0]]['state'] = $parts[1];
// other mapping goes here
$city_array[$parts[0]]['orignal_name'] = $parts[11];
}
另一种更简单的方法是,使用映射并combine分解值
$map = [
'city_name',
'state',
// ..
'original_name'
];
foreach ($lines as $line_num => $value) {
$parts = explode("\t", $value);
$values = array_combine($map, $parts);
$city_array[$parts[0]] = $values;
}
希望这会有所帮助