将索引数组更改为关联数组

时间:2015-12-22 01:46:55

标签: php arrays associative-array

我有一个类似下面的数组

1 => "Los Angeles" 
2 => "California" 
3 => "St. Louis" 
4 => "Missouri" 
5 => "Boston" 
6 => "Massachusetts"

我想将其更改为关联数组,因此每个奇数条目索引都是City,每个偶数条目都是state。 如果这是有道理的,请告诉我。

3 个答案:

答案 0 :(得分:1)

此解决方案适合您

    <?php
  $myarray = array("1" => "Los Angeles" ,
"2" => "California" ,
"3" => "St. Louis" ,
"4" => "Missouri" ,
"5" => "Boston" ,
"6" => "Massachusetts");
    var_dump($myarray);
?>

RESULT-array(6){[1] =&gt; string(11)“洛杉矶”[2] =&gt; string(10)“California”[3] =&gt; string(9)“St. Louis”[4] =&gt; string(8)“Missouri”[5] =&gt; string(6)“Boston”[6] =&gt; string(13)“Massachusetts”}

答案 1 :(得分:0)

数组键的名称不能相同。他们必须是&#39; city1&#39;,&#39; city2&#39;等等

答案 2 :(得分:0)

根据您输入的标题,您希望拥有关联数组,但您希望所有索引都相同,这是不可能的。阅读超出你的问题的行,如果我理解正确,你的数组中的所有奇数项目都是城市,甚至项目是州,你想分开它?然后尝试下面:

jacoco {
      toolVersion = "0.7.1.201405082137"
}

def coverageSourceDirs = {
         '../app/src'
}

task jacocoTestReport(type: org.gradle.testing.jacoco.tasks.JacocoReport, dependsOn: "test"){
    group = "Reporting"
    description = "Generate Jacoco coverage reports"
    classDirectories = fileTree(
          dir: '../app/build/intermediates/classes',
          excludes: ['**/R.class',
                     '**/R$.class',
                     '**/*$ViewInjector*.*',
                     '**/BuildConfig.*',
                     '**/Manifest*.*']
    )
   additionalSourceDirs = files(coverageSourceDirs)
   sourceDirectories = files(coverageSourceDirs)
   executionData = files('../app/build/jacoco/testDebugUnitTest.exec')

   reports {
      xml.enabled = true
      html.enabled = true
   }
}

输出:

<?php
$scrambled_city_state = array(
    1 => "Los Angeles",
    2 => "California",
    3 => "St. Louis",
    4 => "Missouri",
    5 => "Boston",
    6 => "Massachusetts"
);
$cities = array();
$states = array();
foreach ($scrambled_city_state as $key => $city_state) {
    if ($key % 2 == 0) {

        // state
        $states[] = $city_state;
    } 
    else {

        // city
        $cities[] = $city_state;
    }
}
var_dump($cities, $states);
?>