Kasino Kasino - 5 months ago 13
PHP Question

create an array based on two table id's in php

I have two tables. one is 'demo' and other is 'like'.

I am converting array of values into json format using json_encode.

Demo has :

[{ 'id': 1, 'like_id': 2, 'name': 'hero' }, { 'id': 2, 'like_id': 1, 'name': 'villain' }]


Like has :

[{ 'id': 1, 'movie'': 'castle' }, {'id': 2, 'movie' : 'superman' }]


I want to create a new json data as follows:

[{ 'id': 1, 'like_id': [{'id': 2, 'movie' : 'superman'}], 'name': 'hero'},
{ 'id': 2, 'like_id': [{'id': 1, 'movie': 'castle'}], 'name': 'villain'}]


After searching for a while, I think i might need recursive function. But I am not sure how i can write in this scenario.

This is what i tried :

$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;

Answer

The solution using json_decode and str_replace(to prepare for proper decoding) functions:

$demo = "[{ 'id': 1, 'like_id' : 2, 'name': 'hero' }, { 'id': 2, 'like_id': 1, 'name': 'villain' }]";
$likes = "[{ 'id': 1, 'movie': 'castle' }, {'id': 2, 'movie' : 'superman' }]";

$demo_objects = json_decode(str_replace("'",'"',$demo));
$like_objects = json_decode(str_replace("'",'"',$likes));
foreach ($demo_objects as $o) {
    foreach ($like_objects as $l) {
        if ($l->id == $o->like_id) $o->like_id = [$l];
    }

}

print_r(json_encode($demo_objects));

The output:

[
  {"id":1,"like_id":[{"id":2,"movie":"superman"}],"name":"hero"},
  {"id":2,"like_id":[{"id":1,"movie":"castle"}],"name":"villain"}
]