2014-03-06 84 views
1

如何將數據從水平鍵變爲垂直數。如何將數據從水平鍵變爲垂直數

例如:

$array = array( 
    "100" => array("1" => 1000, "2" => 2000), 
    "101" => array("1" => 350, "2" => 500), 
    "102" => array("1" => 1000, "2" => 2000), 
    "103" => array("1" => 10), 
    "104" => array("2" => 5) 
); 


/* Output: 

id key1 key2 
100 1000 2000 
101 350 500 
102 1000 2000 
103 10  0 
104  0  5 

*/ 

回答

0

帶硬編碼索引的直接格式化嵌套陣列:

$array = array( 
    "100" => array("1" => 1000, "2" => 2000), 
    "101" => array("1" => 350, "2" => 500), 
    "102" => array("1" => 1000, "2" => 2000), 
    "103" => array("1" => 10), 
    "104" => array("2" => 5) 
); 

function get_key(&$array, $key, $default=0) { 
    if (isset($array[$key])) { 
    return $array[$key]; 
    } else { 
    return $default; 
    } 
} 

$format = "%5s %5s %5s"; 
echo sprintf($format, "id", "key1", "key2"); 
foreach ($array as $key => $value) { 
    echo sprintf($format, $key, get_key($value, "1"), get_key($value, "2")); 
} 
1

這當然可以以簡單的方式與一些單foreach環解決了,但我更喜歡更通用的解決方案:

//data: 
$array = array( 
    "100" => array("1" => 1000, "2" => 2000), 
    "101" => array("1" => 350, "2" => 500), 
    "102" => array("1" => 1000, "2" => 2000), 
    "103" => array("1" => 10), 
    "104" => array("2" => 5) 
); 

//definitions: formats and values 
$default = 0; 
$title = ['id', 'key1', 'key2']; 
$rowText = "%s\t%s\t%s"; 


//result string 
$keys = array_unique(call_user_func_array('array_merge', array_map('array_keys', $array))); 
sort($keys); 
$result = call_user_func_array('sprintf', array_merge([$rowText], $title)); 
foreach($array as $key=>$row) 
{ 
    $result .= PHP_EOL.call_user_func_array(
     'sprintf', 
     array_merge(
     [$rowText], 
     [$key], 
     array_map(function($x) use ($default, $row) 
     { 
      return isset($row[$x])?$row[$x]:$default; 
     }, $keys) 
    ) 
    ); 
} 

那麼結果將是這樣的:

 
id  key1 key2 
100  1000 2000 
101  350  500 
102  1000 2000 
103  10  0 
104  0  5