如何将这个多维数组转换为具有行和列标题的数组?
如何将类似的数组
array(
0 => array(
'x' => 'x1',
'y' => 'y1',
'count' => 2,
),
1 => array(
'x' => 'x3',
'y' => 'y1',
'count' => 3,
),
2 => array(
'x' => 'x3',
'y' => 'y2',
'count' => 4,
),
3 => array(
'x' => 'x1',
'y' => 'y2',
'count' => 6,
),
4 => array(
'x' => 'x2',
'y' => 'y3',
'count' => 7,
),
5 => array(
'x' => 'x2',
'y' => 'y2',
'count' => 1,
),
)
(这是 SQL 查询的结果)
转换为标头数组:
array('x','y1','y2','y3')
和值数组:
array(
0 => array('x1',2,6,null),
1 => array('x2',null,1,7),
2 => array('x3',3,4,null),
)
我正在尝试采用 查询结果集并将其转换为网格/表。
(呃...抱歉,我没有使用与另一个问题完全相同的示例集)
我很难想出一种很好的、有效的方法来做到这一点。
标头数组应该只是字符串“x”,后跟“y”的所有不同值。为了保持一致性,我们可以按字母顺序对它们进行排序。
最后一个数组对于“x”的每个不同值(组成索引 0)应有 1 行,并且以下索引取自第一个数组中相应 x/y 值的相应“计数”(“y”) '值由'header'数组中的相同索引给出)。缺失值可以是 null
或 0
。
How can I transform an array like
array(
0 => array(
'x' => 'x1',
'y' => 'y1',
'count' => 2,
),
1 => array(
'x' => 'x3',
'y' => 'y1',
'count' => 3,
),
2 => array(
'x' => 'x3',
'y' => 'y2',
'count' => 4,
),
3 => array(
'x' => 'x1',
'y' => 'y2',
'count' => 6,
),
4 => array(
'x' => 'x2',
'y' => 'y3',
'count' => 7,
),
5 => array(
'x' => 'x2',
'y' => 'y2',
'count' => 1,
),
)
(which is the result of an SQL query)
into a header array:
array('x','y1','y2','y3')
and value array:
array(
0 => array('x1',2,6,null),
1 => array('x2',null,1,7),
2 => array('x3',3,4,null),
)
I'm trying take the result set from a query and turn it into a grid/table.
(err...sorry, I didn't use the exact same example set as from the other question)
I'm having trouble with coming up with a nice, efficient way of doing this.
The header array should just be the string "x" followed by all the distinct values for 'y'. For consistency, we can sort them alphabetically.
The last array should have 1 row for every distinct value of 'x' (which makes up the index 0) and the following indexes are taken from the corresponding 'count' for the respective x/y values from the first array (the 'y' value is given by the same index in the 'header' array). Missing values can be null
or 0
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定您是否认为这很好,但它应该很有效。另外,如果您只打算对数据进行
for
...如果您想要foreach
,则可以删除ksort
以获得更高的效率你需要将它们保留在其中。第一个 foreach 是关键位所在的位置..剩下的就是标准化你的结果数组。
Not sure if you consider this nice, but it should be effecient. Also, you could remove the
ksort
s for even better effeciency, if you only plan tofor
over the data... if you wantforeach
you'll need to keep them in.The first foreach is where the critical bit is.. the rest is to normalize your resulting array.