2011-10-28 75 views
-1

我有打印出像數組$array如何在PHP中格式化數組?

Array 
(
[Terry] => Array 
    (
     [2011-10-26] => Array 
      (
       [0] => 69.90 
       [1] => 69.90 
      ) 

    ) 

[Travis] => Array 
    (
     [2011-10-26] => Array 
      (
       [0] => 199.50 
      ) 

     [2011-10-27] => Array 
      (
       [0] => 199.50 
      ) 

    ) 
) 

我試圖將數據放入一個像這樣的表:

NAME  2011-10-26  2011-10-27 
Terry  2    0 
Travis 1    1 

我能得到這樣的計數:

foreach($array as $key => $value){ 
    echo $key; // this will give me the names 
    foreach($value as $keys => $values){ 
     echo $keys; //this will give me the dates 
     echo count($values); // this will give me the count per date 
    } 
} 

我回來的日期是這樣的:2011-10-26 2011-10-26 2011-10-27

我一直在玩這個遊戲一段時間,我用完了想法。

有幫助嗎?

感謝

+0

你不清楚的只是日期格式,或者還就如何創建表?編輯:所以問題是日期被返回爲一個大字符串? –

回答

2
// build a list of all of the available dates 
$dates = array(); 
foreach($array as $key => $value){ 
    $dates = array_merge($value, $dates); 
} 

$dates = array_keys($dates); 

// You may want to sort the date columns here somehow 
echo "Names\t".implode("\t",$dates)."\n"; 
foreach($array as $key => $value){ 
    echo $key; 
    foreach($dates as $d){ 
     echo "\t".(array_key_exists($d, $value) ? count($value[$d]) : 0); 
    } 
    echo "\n"; 
} 
+0

謝謝,這是做到了 – Patrioticcow

0
$result = array(); 
$days = array(); 

foreach ($array as $person => &$dates) 
    $days = array_merge(array_keys($dates), $days); 

$days = array_unique($days); 
sort($days); // Sort days. 

foreach ($array as $person => &$dates) { 
    foreach ($days as &$day) 
     // You can also use array_key_exists instead of '@' to suppress the notice. 
     $result[$day][$person] = @count($dates[$day]); 
} 

var_dump($result); 

結果:

array(2) { 
    ["2011-10-26"]=> 
    array(2) { 
    ["Terry"]=> 
    int(2) 
    ["Travis"]=> 
    int(1) 
    } 
    ["2011-10-27"]=> 
    array(2) { 
    ["Terry"]=> 
    int(0) 
    ["Travis"]=> 
    int(1) 
    } 
}