Arrange a json and write the results

0

I have the following json:

{  
"result":[  
  {  
     “COD”:[10,3,4,11,1],
     "DESCRICAO”:[mouse,teclado,monitor,webcam,celular],
     "ESTOQUE”:[10,2,5,1,0],
     "QUANT_UNID":[ UN,UN,UN,UN,CX]
  }
]
}

In each json field I have a array , how do I write the products in order?

example:

10 mouse 10 UN
3 teclado 2 un
4 monitor 5 un
11 webcam 1 un
1 celular 0 cx
    
asked by anonymous 26.04.2017 / 18:09

2 answers

2

Just to note , this JSON is in an invalid format:

{  
"result":[  
  {  
     “COD”:[10,3,4,11,1],
     "DESCRICAO”:[mouse,teclado,monitor,webcam,celular],
     "ESTOQUE”:[10,2,5,1,0],
     "QUANT_UNID":[ UN,UN,UN,UN,CX]
  }
]
}

Correct it first, it should look like this:

{  
"result":[  
  {  
     "COD":[10,3,4,11,1],
     "DESCRICAO":["mouse", "teclado", "monitor", "webcam", "celular" ],
     "ESTOQUE":[10,2,5,1,0],
     "QUANT_UNID":[ "UN", "UN", "UN", "UN", "CX" ]
  }
]
}

After correcting (I assume it is dynamic) just use for if all items have the same amount:

<?php

$json = '    {
    "result":[
      {
         "COD":[10,3,4,11,1],
         "DESCRICAO":["mouse", "teclado", "monitor", "webcam", "celular" ],
         "ESTOQUE":[10,2,5,1,0],
         "QUANT_UNID":[ "UN", "UN", "UN", "UN", "CX" ]
      }
    ]
    }';

$parsed = json_decode($json);

$results = $parsed->result;

foreach ($results as $item) {
    $cod = $item->COD;
    $qtd = $item->QUANT_UNID;
    $estoque = $item->ESTOQUE;
    $descricao = $item->DESCRICAO;

    $j = count($cod);

    for ($i = 0; $i < $j; $i++) {
        echo $cod[$i], ' ';
        echo $descricao[$i], ' ';
        echo $qtd[$i], ' ';
        echo $estoque[$i], '<br>';
    }
}

If it's an HTML table:

for ($i = 0; $i < $j; $i++) {
    echo '<tr>';
    echo '<td>', $cod[$i], '</td>';
    echo '<td>', $descricao[$i], '</td>';
    echo '<td>', $qtd[$i], '</td>';
    echo '<td>', $estoque[$i], '</td>';
    echo '</tr>';
}

In case I used foreach because I suppose that results can receive multiple data, like:

"result":[  
  {  
     "COD": ...,
     "DESCRICAO": ...,
     "ESTOQUE": ...,
     "QUANT_UNID": ...
  },
  {  
     "COD": ...,
     "DESCRICAO": ...,
     "ESTOQUE": ...,
     "QUANT_UNID": ...
  },
  {  
     "COD": ...,
     "DESCRICAO": ...,
     "ESTOQUE": ...,
     "QUANT_UNID": ...
  },
]
    
26.04.2017 / 18:25
0

You transform json into an object and can use for to read each object. Something like this (assuming that everything, COD, DESCRIPTION, STOCK, and QUANT_UNID have the same number of elements):

$valores = "";
$obj = json_decode($dadosJson, TRUE);
for($i=0; $i<count($obj['COD']); $i++) {
    $valores .= $obj['COD'][$i] . " " .$obj['DESCRICAO'][$i] . " " . $obj['ESTOQUE '][$i] . " " . $obj['QUANT_UNID'][$i] . "\n";
}
echo $valores;
    
26.04.2017 / 18:20