2

I have an array like this..

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) ""
    }...

Like wise

For creating the above array I did this

$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);
}

Is there any way where I can make it to the below format because it would be easier for me to search in this format since the data is huge in city.data file

array(26053){
    ["New York"]=>.......
    ["Mexico"] => ...... }

Thanks for the help

antonio
  • 18,044
  • 4
  • 45
  • 61
MixedVeg
  • 319
  • 2
  • 15

1 Answers1

0

yes, you can totally do that (as long as city names are 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];   
}

another simpler approach is, having a mapping and combine the exploded values

$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;
}

Hopefully this helps

Community
  • 1
  • 1
code-jaff
  • 9,230
  • 4
  • 35
  • 56