私は2つのテーブルを持っています。 1つは「デモ」、もう1つは「好き」です。PHPの2つのテーブルIDに基づいて配列を作成します
json_encodeを使用して、値の配列をjson形式に変換しています。
デモがあります
[{ 'id': 1, 'like_id': 2, 'name': 'hero' }, { 'id': 2, 'like_id': 1, 'name': 'villain' }]
などがあります。
[{ 'id': 1, 'movie'': 'castle' }, {'id': 2, 'movie' : 'superman' }]
私は次のように新しいJSONデータを作成したい:
[{ 'id': 1, 'like_id': [{'id': 2, 'movie' : 'superman'}], 'name': 'hero'},
{ 'id': 2, 'like_id': [{'id': 1, 'movie': 'castle'}], 'name': 'villain'}]
しばらく検索した後、私は思います私は再帰的な関数が必要かもしれません。しかし、私はこのシナリオでどのように書くことができるのか分かりません。
これは私が試したものです:
$pages = array();
$demo = Object('demo');
$like = Object('like');
foreach ($demo as $d) {
foreach ($like as $l) {
$response = array(
'id' => $d['id'],
'like_id' => array(
'id' => $l['id'],
'movie' => $l['movie']
),
'name' => $d['name']
);
array_push($pages, $response);
}
}
$res = json_encode($pages);
echo $res;
あなたは再帰を必要としません。ちょうどネストされた 'foreach'ループ。 – Barmar
結果に 'like_id'で配列が必要なのはなぜですか? 'Demo'にはID番号が1つしかないので、' Like'のオブジェクトに置き換えてください。 – Barmar
@Barmarネストされたforeachを試しました。しかし、それはより多くの回数を倍数化して結果を印刷します。 – Kasino