Output two-dimensional array
Ok, I'm still struggling with my arrays... I have created a two-dimensional array and saved into a session to get results on another page: $_SESSION['myARRAY']
print_r($_SESSION['myARRAY']);
// will output:
Array ( [Car] => Array ( [0] => 1 [1] => 9 [2] => 0 )
[Truck] => Array ( [0] => 2 [1] => 10 [2] => 0 )
[Bus] => Array ( [0] => 1 [1] => 8 [2] => 2 ))
Now I need to output the data into the following format:
$xls->addRow(Array("Car",1,9,0));
$xls->addRow(Array("Truck",2,10,0));
$xls->addRow(Array("Bus",1,8,2));
I tried to do something like this:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$arr[$key] = $key;
foreach($value AS $k => $v) {
$arr[$key] = $v;
}
$xls->addRow($arr[$key]);
}
but it did not really wor开发者_StackOverflow社区k. I think I'm close but not quite there...
$value
is already an array. Now you only need to prepend the $key
to it. You could use array_unshift
:
foreach($_SESSION['myARRAY'] AS $key => $value) {
array_unshift($value, $key);
$xls->addRow($value);
}
Of course if you do this more than once, you should consider storing the consolidated array.
I'd probably use array_unshift
as it seems like a more appropriate way to solve this problem, but you could also do it like:
foreach($_SESSION['myARRAY'] AS $key => $value) {
$xls->addRow(array_merge(array($key), $value));
}
精彩评论