目前我正在尝试重构数据库查询结果的多维数组。目标是最终将数组编码为JSON,如下所示,但我编写的php函数不起作用(参见末尾的代码):
desiredJSONoutput = {"TypeA":[
{"1":[
{"TypeB":[4,5]},
{"TypeC":[7,8,4]}]},
{"2":[
{"TypeB":[2,3]},
{"TypeC":[6]}]},
{"4":[
{"TypeB":[33,12]},
{"TypeC":[908]}]}]}
数据库结构是:
fromType fromID toType toID
-----------------------------------------------------
TypeA 1 TypeB 4
TypeA 1 TypeB 5
TypeA 1 TypeC 7
TypeA 1 TypeC 8
TypeA 1 TypeC 4
TypeA 2 TypeB 2
TypeA 2 TypeB 3
TypeA 2 TypeC 6
TypeA 2 TypeB 33
TypeA 2 TypeB 12
TypeA 2 TypeC 908
我当前的sql查询的结果是这个php数组:
Array
(
Array
(
['fromType'] => 'TypeA'
['fromID'] => '1'
['toType'] => 'TypeB'
['toID'] => '4'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '1'
['toType'] => 'TypeB'
['toID'] => '5'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '1'
['toType'] => 'TypeC'
['toID'] => '7'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '1'
['toType'] => 'TypeC'
['toID'] => '8'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '1'
['toType'] => 'TypeC'
['toID'] => '4'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '2'
['toType'] => 'TypeB'
['toID'] => '2'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '2'
['toType'] => 'TypeB'
['toID'] => '3'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '2'
['toType'] => 'TypeC'
['toID'] => '6'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '3'
['toType'] => 'TypeB'
['toID'] => '33'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '3'
['toType'] => 'TypeB'
['toID'] => '12'
)
Array
(
['fromType'] => 'TypeA'
['fromID'] => '3'
['toType'] => 'TypeC'
['toID'] => '908'
)
)
和我在编码到JSON之前需要的重构数组我认为是:
Array
(
['TypeA'] => Array
(
['1'] => Array
(
['TypeB'] => Array
(
[0] => 4
[1] => 5
)
['TypeC'] => Array
(
[0] => 7
[1] => 8
[2] => 4
)
)
['2'] => Array
(
['TypeB'] => Array
(
[0] => 2
[1] => 3
)
['TypeC'] => Array
(
[0] => 6
)
)
['3'] => Array
(
['TypeB'] => Array
(
[0] => 33
[1] => 12
)
['TypeC'] => Array
(
[0] => 908
)
)
)
)
我不确定为什么以下的PHP代码没有将返回的php数组重组为我想要的结构的技巧:
class Utilities {
public function linksReEncode($rowsArray) {
$result = array();
foreach ($rowsArray as $row) {
$fromtype = $row['fromtype'];
$fromID = $row['fromID'];
$toType = $row['toType'];
$toID = $row['toID'];
$arr = $result[$fromType][$fromID][$toType];
array_push($arr, $toID);
}
}
}
修改 基于进一步的研究和@Waygood的第一个答案,这里是我正在使用的功能,它正在运行。我想知道是否有必要检查现有密钥,以及这是否是实现这一目标的最经济的方法
public function linksReEncode($rows) {
$result = array();
foreach ($rows as $row) {
$fromType = $row['fromType'];
$fromID = $row['fromID'];
$toType = $row['toType'];
$toID = $row['toID'];
if(!array_key_exists($fromType, $result))
$result[$fromType] = array();
if(!array_key_exists($fromID, $result[$fromType]))
$result[$fromType][$fromID] = array();
if(!array_key_exists($toType, $result[$fromType][$fromID]))
$result[$fromType][$fromID][$toType] = array();
array_push($result[$fromType][$fromID][$toType], $toID);
}
return $result;
}
答案 0 :(得分:1)
你只是在每个循环中重新定义$ arr,而不是改变$ result
变化:
$arr = $result[$fromType][$fromID][$toType];
array_push($arr, $toID);
为:
$result[$fromType][$fromID][$toType][]=$toID;