這當然可以以簡單的方式與一些單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