2017-09-19 26 views
0

請在陣列中的轉換幫助從一種形式到另一個我得到這個數組轉換數組類型在PHP

Array ( 
    [mpr_last_month] => 376431 
    [mpr_month] => 03 
    [total_boys_all_6m_36m] => 5550225 
    [total_girls_all_6m_36m] => 5215529 
    [total_boys_all_36m_72m] => 4209639 
    [total_girls_all_36m_72m] => 4149613 
    [total_pse_boys_36m_72m] => 4442301 
    [total_pse_all_girls_36m_72m] => 4413446 
    [total_pregnanting] => 2209158) 



Array (
    [mpr_last_month] => 448216 
    [mpr_month] => 04 
    [total_boys_all_6m_36m] => 7153209 
    [total_girls_all_6m_36m] => 6798913 
    [total_boys_all_36m_72m] => 5175846 
    [total_girls_all_36m_72m] => 5105460 
    [total_pse_boys_36m_72m] => 5290617 
    [total_pse_all_girls_36m_72m] => 5263340 
    [total_pregnanting] => 2944612 
    ) 

Array ( 
    [mpr_last_month] => 448253 
    [mpr_month] => 05 
    [total_boys_all_6m_36m] => 11742417 
    [total_girls_all_6m_36m] => 6362815 
    [total_boys_all_36m_72m] => 4879252 
    [total_girls_all_36m_72m] => 4756805 
    [total_pse_boys_36m_72m] => 5344042 
    [total_pse_all_girls_36m_72m] => 5095155 
    [total_pregnanting] => 2852864 

    ) 

Array ( 
    [mpr_last_month] => 470848 
    [mpr_month] => 06 
    [total_boys_all_6m_36m] => 6552523 
    [total_girls_all_6m_36m] => 6217771 
    [total_boys_all_36m_72m] => 4613019 
    [total_girls_all_36m_72m] => 4551685 
    [total_pse_boys_36m_72m] => 5182666 
    [total_pse_all_girls_36m_72m] => 5165730 
    [total_pregnanting] => 2746293 
    ) 

Array ( 
    [mpr_last_month] => 465489 
    [mpr_month] => 07 
    [total_boys_all_6m_36m] => 6638749 
    [total_girls_all_6m_36m] => 6310676 
    [total_boys_all_36m_72m] => 4801665 
    [total_girls_all_36m_72m] => 4657764 
    [total_pse_boys_36m_72m] => 5020964 
    [total_pse_all_girls_36m_72m] => 5051785 
    [total_pregnanting] => 2815773 

    ) 

我想這

name: 'mpr_last_month', 
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175,123,123,123,123] 

。 。 。 。 。 。 。 。

+3

你有什麼已經嘗試過? – JustBaron

回答

0

您可以使用array_column函數。但請注意,該功能僅適用於PHP> = 5.5.0。試試這個:

//example data 
$array = [ 
    ['a' => 2, 'b'=>3, 'c'=>6], 
    ['a' => 12, 'b'=>13, 'c'=>16], 
    ['a' => 22, 'b'=>23, 'c'=>26], 
]; 


$result = []; 

//get indexes from first element of array 
$indexes = array_keys($array[0]); 

foreach($indexes as $index) { 
    $result[$index] = array_column($array, $index); 
} 

而且結果是:

Array 
(
    [a] => Array 
     (
      [0] => 2 
      [1] => 12 
      [2] => 22 
     ) 

    [b] => Array 
     (
      [0] => 3 
      [1] => 13 
      [2] => 23 
     ) 

    [c] => Array 
     (
      [0] => 6 
      [1] => 16 
      [2] => 26 
     ) 

) 
+0

哇,array_column()函數非常整潔!不知道,謝謝先生。 –

+0

@ManuelMannhardt,我很高興你已經學會了新的東西:) – aslawin

+0

讓我們老實說,你不能做學習PHP的:) –

2

最簡單的方法是foreach循環。

$newData = []; 
foreach ($yourArray as $innerArray) { 
    foreach ($innerArray as $key => $value) { 
     $newData[$key][] = $value; 
    } 
} 

它循環遍歷第一個數組(包含所有其他數組),遍歷每個內部數組並將其存儲在正確位置。