2015-11-08 103 views
1

與值的新陣列我有一個包含單個陣列,內容類似這樣的數組(從數據庫中拉):創建從其他陣列

Array 
(
[0] => Array 
    (
     [date] => 2014-11 
     [time] => 2135 
     [name] => John 
    ) 

[1] => Array 
    (
     [date] => 2014-11 
     [time] => 5496 
     [name] => Adam 
    ) 

[2] => Array 
    (
     [date] => 2014-12 
     [time] => 1526 
     [name] => John 
    ) 

[3] => Array 
    (
     [date] => 2014-12 
     [time] => 5481 
     [name] => Adam 
    ) 
[4] => Array 
    (
     [date] => 2014-12 
     [time] => 3476 
     [name] => Lizzie 
    ) 
) 

我想要做的是建立一個新的多維基於前面的數組,數組的同月通過以下方式結合在一起的陣列:

Array 
(
[0] => Array 
    (
     [date] => 2014-11 
     [John] => 2135 
     [Adam] => 5496 
    ) 

[1] => Array 
    (
     [date] => 2014-12 
     [John] => 1526 
     [Adam] => 5481 
     [Lizzie] => 3476 
    ) 
) 

我也想看看不同的陣列功能,但根本無法得到關於如何實現我的身邊這....

回答

1

看看下面的代碼片段。

$output = array(); // Where the output will be saved 

foreach ($input as $row) { // Need to process the original input array 

    $date = $row['date']; // Grouping by the date value, thus we use it as an index in an associative array 

    if (empty($output[$date])) { 
     $output[$date] = array('date' => $date); // Make sure the 'date' value is in the final output 
    } 

    $output[$date][$row['name']] = $row['time']; // Actual values, e.g., [Adam] => 5496 
} 

$output = array_values($output); // Removing original indexes from the associative array 

問題中所需的數組結構有點奇怪,但沒有問題問。

+0

感謝您的詳細建議!它像廣告一樣工作。 我想要這樣的數組的原因是因爲數據將被用於堆疊條形圖,並且正如我所看到的,這將成爲提供給Google API的最佳格式。 我絕對非常開放其他建議,如果有的話。我是一個非常小的PHP開發人員,這可能也反映了我的思維方式:-) – DanTheDane