2016-10-09 114 views
0

我有一些數據,從MySQL查詢這種方式來在一個平面陣列:PHP轉換平板嵌套多維數組中的foreach循環

0 => Array 
    indcode => "A00" 
    indlabel => "Code label text" 
    description => "More explanations" 
    1 => Array 
    indcode => "NA0" 
    indlabel => "Un-classified A" 
    description => "Un-classified A" 
    2 => Array (3) 
    indcode => "A01" 
    indlabel => "Code Label text" 
    description => "More explanations" 
    3 => Array (3) 
    indcode => "A02" 
    indlabel => "Code label text" 
    description => "More explanations" 

我想窩這種方式:

A00 => Array 
    indlabel => "Code label text" 
    description => "More explanations" 
    NA0 => Array 
    indlabel => "Un-classified A" 
    description => "Un-classified A" 
    A01 => Array 
    indlabel => "Code Label text" 
    description => "More explanations" 
    A02 => Array 
    indlabel => "Code label text" 
    description => "More explanations" 

所以在我的CMS我在使用中發現了一個非常整潔的代碼確實嵌套:

foreach ($dimsDesc as $desc) { 
$descriptions[$desc['indcode']][$desc['indlabel']] = $desc['description']; 
} 

這一工程b我沒有找到如何在同一級別(=等號的另一側)保留indlabel和描述。如果你有其他一些例子的鏈接或者這個構造的一個很好的參考,那將會被讚賞,因爲我將用它來構建動態的報告......並且現在PDO查詢有點不在我的觸及。我還用array_column()NULL其作品,但我有更多的進入複雜的數據結構...

回答

1

你幾乎沒有,只是改變你的foreach循環通過以下方式,

foreach ($dimsDesc as $desc) { 
    $descriptions[$desc['indcode']]['indlabel'] = $desc['indlabel']; 
    $descriptions[$desc['indcode']]['description'] = $desc['description']; 
} 

或者,

foreach ($dimsDesc as $desc) { 
    $descriptions[$desc['indcode']] = array('indlabel' => $desc['indlabel'], 'description' => $desc['description']); 
} 

這裏的文檔,

+0

謝謝,所有人都會工作,但特別是第一個例子,即使它看起來不如第二個簡潔,它也幫助我理解我錯過了什麼! –

+0

非常感謝。我想知道是否有一些(書籍,在線文檔,...),我可以找到一些例子或解釋。我特別想知道爲什麼這會起作用(而不是覆蓋值或複製數組......).. –

+0

@ Joel.O這裏的文檔,[http://php.net/manual/en/language.types.array .PHP#language.types.array.syntax.modifying](http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying) –

1

試試這個,

<?php 
foreach ($dimsDesc as $desc) { 
    $descriptions[$desc['indcode']] = array( 
     'indlabel' => $desc['indlabel'], 
     'description' => $desc['description'] 
    ); 
} 
?> 
+0

就像一個魅力:)謝謝! –