我有一些代码可以创建一个多维数组,但我的结果似乎是一个数组数组,这不是我想要的。我想压扁这个数组。如何更改此数组结果:
Array
(
[0] => Array
(
[0] => Array
(
[2011-11-18 00:00:00] => C
)
[1] => Array
(
[2011-11-18 00:00:00] => I
)
[2] => Array
(
[2011-11-18 00:00:00] => S
)
)
[1] => Array
(
[0] => Array
(
[2011-11-22 00:00:00] => C
)
[1] => Array
(
[2011-11-22 00:00:00] => S
)
)
)
进入不是“数组数组”的东西?以下是创建数组数组的代码:
$qrybilled = $this->db->query("SELECT tbltc.BILLED FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario GROUP BY BILLED");
$x = 0; $arr_billed = array();
foreach ($qrybilled->result() as $row) {
$qry = $this->db->query("SELECT tbltc.BILLED, tbltc.TC, tbltc.CAT FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario AND tbltc.BILLED = '".$row->BILLED."' GROUP BY TC");
$tmp = array();
foreach ($qry->result() as $row) {
$tmp[] = array( $row->BILLED => $row->TC);
}
$arr_billed[] = $tmp;
}
$data['billed'] = $arr_billed;
如果您可以建议一种更好的方法来构建数组,使其不是“数组数组”,那就太棒了。谢谢你的帮助。
NickB的答案对我来说非常合适,并产生了以下输出,这正是我所寻求的:
Array
(
[2011-11-18 00:00:00] => Array
(
[0] => C
[1] => I
[2] => S
)
[2011-11-22 00:00:00] => Array
(
[0] => C
[1] => S
)
)
答案 0 :(得分:3)
您可以循环遍历数组中的所有条目以创建新数组。
$result = array();
foreach( $array as $inner_array)
{
foreach( $inner_array as $entry)
{
foreach( $entry as $key => $value)
{
$result[ $key ][] = $value;
}
}
}
<强>输出:强>
array(2) {
["2011-11-18 00:00:00"]=>
array(3) {
[0]=>
string(1) "C"
[1]=>
string(1) "I"
[2]=>
string(1) "S"
}
["2011-11-22 00:00:00"]=>
array(2) {
[0]=>
string(1) "C"
[1]=>
string(1) "S"
}
}
答案 1 :(得分:1)
虽然在同一个数组中使用同一个键不止一个,但您可以返回一个更简单(但仍然是嵌套)的结构(一对对象列表 - 正如某些语言所称的那样)。
假设您的数据被称为$data
:
$compactData = array();
array_walk_recursive($data, function($value, $key) use (&$compactData) {
$compactData[] = array($key, $value);
});
print_r($compactData);
打印:
Array
(
[0] => Array
(
[0] => 2011-11-18 00:00:00
[1] => C
)
[1] => Array
(
[0] => 2011-11-18 00:00:00
[1] => I
)
[2] => Array
(
[0] => 2011-11-18 00:00:00
[1] => S
)
[3] => Array
(
[0] => 2011-11-22 00:00:00
[1] => C
)
[4] => Array
(
[0] => 2011-11-22 00:00:00
[1] => S
)
)