データベースからの単純化されたテーブルは次のとおりです
。
Id Name
=======
1 A
2 B
3 C
画像
Id ParentId ImageData
=====================
1 2 sthsth
2 1 sthsth
3 1 sthsth
これらをデータベースから取得し、ツリーのような構造を作成する必要があります (これらの親子関係の 4 つのテーブルがあります)、JSON にエンコードします。PHP + Zend を使用しています。これまでの私の解決策は、各テーブルへのクエリを作成し、それを JSON にエンコードしてから、手動で子 JSON を親 JSON に挿入することでした。これを行うより良い方法はありますか?
これまで試した
private function insertAsLastInJson($json, $name, $insert)
{
if(strlen($json) < 2)
return '{' . $insert . '}';
$in = ",\"$name\":$insert";
return substr($json, 0, strlen($json) - 1) . $in;
}
そして、私はそれを次のように使用しました:
$json = Zend_Json::encode($imageContainerRow); //$imageContainerRow contains single 'ImageContainer' row fetched from database
insertAsLastInJson($json, "images", $imagesRows); //$imagesRows contains multiple 'Images' rows fetched from database and encoded to JSON, separated by commas and everything is in beetween [ ].
JSON の例は次のようになります。
{"Id":1,"Name":"A","Images":[{"Id":2,"ParentId":1,"ImageData":"sthsth"},
{"Id":3,"ParentId":1,"ImageData":"sthsth"}]}
これにはいくつかの括弧の挿入が必要でしたが、全体としては機能しました。これを行うより良い方法はありますか?