[英]PHP Creating an indexed array vs associative array
我在下面調用 getTeams function 以獲得一個簡單的團隊名稱列表,但如果沒有兩步過程,我無法讓它工作。 如果我使用
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
看起來它正在創建一個關聯數組,其中鍵是從 0 開始的數字?
我可以使它工作使用
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
for ($i= 0; $i < count($teamNames); $i++){
$teamNames2[$teamNames[$i]]=$teamNames[$i];
}
return $teamNames2;
}
我認為這可能是因為第一個數組是關聯數組,而第二個數組是創建索引數組? 這個思維過程正確嗎? 如果是這樣,在 foreach 循環中創建索引數組的正確方法是什么?
不知道你的數組:如果你想創建一個關聯數組,你應該給它的元素一個鍵。 所以而不是
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
代碼在哪里
$teamNames[]
將始終向您的數組添加索引條目。
如果您想要關聯條目,請改用鍵。 就像是
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[$team['key']] = $team['displayName'];
}
return $teamNames;
}
$teamNames
現在應該返回一個關聯數組
您可以使用array_column()
來提取數據,並且使用array_combine()
來進行關聯。
以下代碼將生成與第二個getTeams()
相同的 output :
$teams = [ // Sample data
['team' => ['displayName' => 'a']],
['team' => ['displayName' => 'b']],
['team' => ['displayName' => 'c']],
['team' => ['displayName' => 'd']],
];
// Extract display names
$teams = array_column(array_column($teams, 'team'), 'displayName');
// Make is associative
$teams = array_combine($teams, $teams);
var_dump($teams);
Output:
array(4) {
["a"] => string(1) "a"
["b"] => string(1) "b"
["c"] => string(1) "c"
["d"] => string(1) "d"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.