2016-07-27 68 views
0

我有一個多維數組,我正在嘗試使用,這裏是它的樣子。多維數組不能返回正確的值

$states = array(
"California" => array(
    "state" => "California", 
    "abbr" => "CA", 
    "city" => "Sacramento", 
    "county" => "Sacramento", 
    "zip" => "95632" 
), 
"Washington" => array(
    "state" => "Washington", 
    "abbr" => "WA", 
    "city" => "Seattle", 
    "county" => "King", 
    "zip" => "98101" 
), 
"Texas" => array(
    "state" => "Texas", 
    "abbr" => "TX", 
    "city" => "San Antonio", 
    "county" => "Bexar", 
    "zip" => "78251" 
), 
"Florida" => array(
    "state" => "Florida", 
    "abbr" => "FL", 
    "city" => "Orlando", 
    "county" => "Orange", 
    "zip" => "32801" 
), 
); 

當運行foreach循環以從陣列的第一級得到的鑰匙我得到的

California Washington Texas Florida 

預期輸出。然而我需要訪問所述陣列的第二層。例如,我需要加州[ '簡稱']所以這是我運行代碼:

foreach (array_keys($states) as $state) { 
    echo $state['abbr']; 
} 

,而不是領

CA WA TX FL 

就像我希望我得到

C W T F 

關於我在做什麼的任何想法都是錯誤的?

回答

1

array_keys($states)正在恢復

array("California", "Washington", "Texas", "Florida") 

所以foreach循環只是迴應每個狀態的第一個字符。循環遍歷整個陣列而不僅僅是密鑰:

foreach ($states as $name => $details) { 
    echo $details['abbr']; 
} 
1

您可以使用兩個foreach來訪問每個城市(數組)內的元素。這不是最快的方法,但知道它是很好的。

// access the first layer 
foreach($states as $state) 
{ 
    // access the second layer 
    foreach($state as $key => $element) 
    { 
    // if the key is equal to 'abbr', echo it's value 
    echo ($key == 'abbr') ? $state[$key] : ''; 
    echo ' '; 
    } 
} 

這將輸出:

CA WA TX FL

0

剛:

foreach($states as $state) { 
    foreach($state as $v) { 
     echo $v['abbr']; 
    } 
} 
+0

雖然此代碼段可以解決的問題,[包括一個解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高質量您的帖子。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

1
foreach(array_keys($states) as $state) { 
    echo $state; 
} 

會響應按鍵,因爲你遍歷鍵,而不是數組。要獲得縮寫,你應該做的

foreach($states as $state) { 
    echo $state['abbr']; 
} 

如果你要循環的關鍵,並在同一時間價值兩,試試這個

foreach($states as $key=>$state) { 
    echo "$key: {$state['abbr']}"; 
} 
0

只能切出array_keys。您需要該數組的整個元素,而不僅僅是數組的鍵。

foreach ($states as $state) 
{ 
    echo $state['abbr']; 
}