'Combining a describing and one array with data
I'm looking for an easy way to combine two arrays.
$lang = array('de' => 'german', 'es' => 'spanish', 'nl' => 'dutch');
I have X sites which should have a table like this:
language value1 value2 value3
--------------------------------------
de 123 56 097
en 84 129 123
es 0 0 0
nl 0 0 0
Site Y could look like this:
language value1 value2 value3
--------------------------------------
de 9 12 123
en 32 65 156
es 0 0 0
nl 23 12 89
This table could differ on every site, but I want every language to be displayed even if it has no values. The list of languages should be separated to extend it later.
Solution 1:[1]
I was doing this from the CLI, so there's no HTML structure to it. I'm not sure if I fully understood everything you were trying to do, but here's what I have:
$lang = array('de' => 'german', 'es' => 'spanish', 'nl' => 'dutch', 'en' => 'english');
$sites = array(
'value1' => array('en' => 35, 'de' => 54),
'value2' => array('nl' => 543, 'en' => 234, 'es' => 2),
'value3' => array('es' => 39)
);
printf("%-10s", "language");
$site_names = array_keys($sites);
foreach($site_names as $site_name)
{
printf("%-10s", $site_name);
}
printf("\n%s\n", str_repeat('-', (count($site_names) + 1) * 10));
foreach($lang as $lang_short => $lang_long)
{
printf("%-10s", $lang_short);
foreach($sites as $site_name => $site_values)
{
printf("%-10d", isset($site_values[$lang_short]) ? $site_values[$lang_short] : 0);
}
printf("\n");
}
Output:
language value1 value2 value3 ---------------------------------------- de 54 0 0 es 0 2 39 nl 0 543 0 en 35 234 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Cooper |