How to relate 2 json tables to php?

Asked

Viewed 140 times

1

Good afternoon, my friends. I’m developing a plan system where I need to link 2 json tables to filter the data.

But I’m not succeeding. I tried to relate them by creating 2 foreachs and trying to create a link between the 2, but I was not successful.

One of my tables is called plans.json and contains data in array

Plans.json

    [
      {
        "codigo": 1,
        "minimo_vidas": 1,
        "faixa1": 10.00,
        "faixa2": 12,
        "faixa3": 15.00
      }
    ]

second table is the.json prices

    [
      {
        "registro": "reg1",
        "nome": "Bitix Customer Plano 1",
        "codigo": 1
      }
    ]

the two the "foreign key" code as referencing, however I am not able to join the two and display them.

Could someone help me find some solution ?

1 answer

0


In this case, I suggest using json_decode and turn them into an array, then process these arrays to perform the 'relationship'. Ideally, the API would already be returning this related data within a json object property.

$planos = json_decode($jsonPlanos, true);
$precos = json_decode($jsonPrecos, true);

//indexar array planos:
$idxPlanos = [];
foreach ($planos as $p){
   $idxPlanos[$p['codigo']] = $p;
}

foreach ($precos as $p){
   $idxPlanos[$p['codigo']]['preco'] = $p; 
}

//liberar arrays
unset($precos); unset($planos);
//exibir array pronto
var_dump($idxPlanos);
  • 1

    Thank you very much, friend, you helped me so much. Its code worked perfect, I only had to put a 'true' in the line $planos = json_decode($jsonPlanos, true); and also in the price line, and ran too smooth. Thanks again. STRONG HUG

Browser other questions tagged

You are not signed in. Login or sign up in order to post.