2009-12-12 108 views
1

一個嵌套的多維數組我有一個數組,像這樣:多維數組在PHP中

sid   sname    did    dname 
    1   Basketball   1     Mini 
    1   Basketball   3     Cadet 
    2   Baseball    8    Little League 
    2   Baseball    6    Junior League 
    1   Basketball   5    Masters 

我試圖讓這個並將其轉換爲一個嵌套的數組,像這樣:

array('Basketball' => array(
         'id' => 1, 
         'divisions' => array(
              1 => 'Mini', 
              3 => 'Cadet', 
              5 => 'Masters' 
             ) 
         ), 
     'Baseball' => array(
         'id' => 2, 
         'divisions' => array(
              8 => 'Little League', 
              6 => 'Junior League' 
             ) 
         ) 
); 

而且我正在使用這個不工作的foreach循環,它取代了每個分區條目,因此我只剩下一個分區條目,這是最後一個條目。

$result = ''; 
foreach($row as $r) 
{ 

    $result[$r['sname']] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname'])); 

} 

這foreach循環給了我這樣的結果:

array('Basketball' => array(
         'id' => 1, 
         'divisions' => array(
              5 => 'Masters' 
             ) 
         ), 
     'Baseball' => array(
         'id' => 2, 
         'divisions' => array(
              6 => 'Junior League' 
             ) 
         ) 
); 

我不明白什麼是錯在這裏..任何人可以幫助我在這裏?

回答

3

的問題是,你重新定義每次$result[$r['sname']]。如果尚未定義,則只需定義它。

$result = array(); // initialize this to an appropriate type! 
foreach($row as $r) 
{ 

    if(!isset($result[$r['sname']])) 
    { 
     $result[$r['sname']] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname'])); 
     continue; 
    } 
    $result[$r['sname']]['divisions'][$r['did']] = $r['dname']; 

} 
0

事先檢查是否存在密鑰isset()array_key_exists(),以便它不會被重寫。

0

我想你想:

$result[$r['sname']][] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname'])); 
1
$result = array(); 
foreach($row as $r) 
{ 

    $result[$r['sname']]['id'] = $r['sid']; 
    $result[$r['sname']]['divisions'][$r['did']] = $r['dname']; 

} 
+0

+1假設它的工作原理,這是一個非常優雅的讀取。當然,它每次都重新初始化'id'值,但這並不昂貴。 –

+0

順便說一句...這工作。謝謝 – moleculezz

0
$result = array(); 
foreach($row as $r) 
{ 
    if(isset($result[$r['sname']])) 
    { 
     array_push($result[$r['sname']], array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname']))); 
    } 
    else 
    { 
     $result[$r['sname']] = array('id' => $r['sid'], 'divisions' => array($r['did'] => $r['dname'])) 
    } 
} 

什麼目前你正在做的是重寫$result[$r['sname']]的條目,所以它只會永遠有它的一個陣列。

我使用if因爲$array[] =是快於array_pushsee php docs