2015-04-12 71 views
1

我有關聯期多維陣列保持計數鍵

Array 
(
[1] => Array 
    (
     [Chapter] => Name 1 
     [Section] => Array 
      (
       [1] => Section name 1 
       [2] => Section name 2 
       [3] => Section name 3 
      ) 
    ) 

[2] => Array 
    (
     [Chapter] => Name 2 
     [Section] => Array 
      (
       [1] => Section name 4 
       [2] => Section name 5 
      ) 
    ) 
) 

我想繼續鍵數字計數爲第名稱1,第名稱2,節名稱3,節名稱4,段名5.陣列的按鍵將匹配部分的名稱 所以它會看起來像這樣

Array 
(
[1] => Array 
    (
     [Chapter] => Name 1 
     [Section] => Array 
      (
       [1] => Section name 1 
       [2] => Section name 2 
       [3] => Section name 3 
      ) 

    ) 

[2] => Array 
    (
     [Chapter] => Name 2 
     [Section] => Array 
      (
       [4] => Section name 4 
       [5] => Section name 5 
      ) 
    ) 
) 

我試圖做

$count = 0; 
foreach ($sections as $key => $value) { 
    foreach ($value['Section'] as $k => $val) { 
     $count ++; 
     $value['Section'][$count] = $value['Section'][$k]; 
     unset($value['Section'][$k]); 
    } 
} 

,但它仍然指望從1

+0

路過你有兩個使用&$值。 –

+0

什麼是$值? – user45669

+0

做一個參考而不是一個副本,只有你的更改會在下面的答案中發生 –

回答

1

每個陣列試試這個

$count = 0; 
foreach ($sections as $key => $value) { 
    $newSection = array(); 
    foreach ($value['Section'] as $k => $val) { 
     $count++; 
     $newSection[$count] = $val; 
    } 
    $sections[$key]['Section'] = $newSection; 
} 

如果使用&$value,那麼你的第一部分將是空的,因爲你將unset他們。

因此,使用正確的密鑰將您的部分名稱添加到新數組中,並在Section foreach loop之後覆蓋部分值。

用於解釋參考

$count = 0; 
// Pass $value as reference 
foreach ($sections as $key => &$value) { 
    $newSection = array(); 
    foreach ($value['Section'] as $k => $val) { 
     $count++; 
     $newSection[$count] = $val; 
    } 

    // Overwrite reference "Section" 
    // This will manipulate $sections array 
    $value['Section'] = $newSection; 

    // Without reference, overwrite $sections array 
    $sections[$key]['Section'] = $newSection; 
} 
+0

這就是我一直在尋找,謝謝!很好,很清楚! – user45669