現在、データベース クエリの結果である多次元配列を再構築しようとしています。目標は最終的に次のように配列を 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;
}