How to group and add JSON values in PHP strings

Asked

Viewed 140 times

1

I have a file named json data. structured as follows:

{
  "price_usd": [
    [
      1588464000000,
      10,
      8
    ],
    [
      1588464000000,
      10,
      8
    ],
    [
      1588464000000,
      10,
      8
    ],
    [
      1588464000000,
      3,
      2.8
    ],
    [
      1588550400000,
      3,
      2.8
    ],
    [
      1588550400000,
      3,
      2.8
    ]
  ]
}

The first variable represents the date of a sale, the second variable the sale price of the product, the third variable is the purchase price.

I would like to define in PHP strings, the following three variables with the file data in example, where the dates will be grouped and the values summed:

$data = "1588464000000, 1588550400000";
$venda = "33, 6";
$compra = "26.8, 5,6";

To extract the data from the file I use:

$JSON = file_get_contents('dados.json');

I would like to obtain the sums of the values (purchase price and sale price) grouped by the dates, that is, add up everything that was sold "yesterday" and "today" for example.

  • As far as he wrote "...the third variable is the purchase price." it is clear, from the moment he wrote "... Would you like to set in PHP strings..." onwards is not understandable. What do you want to do? Put $data, venda and $compra in an array within your JSON file?

  • 1

    @Augustovasques would like to get the sums of the values (purchase price and sale price) grouped by the dates, ie, add up everything that was sold "yesterday" and "today" for example.

  • talun, put in the question that you explained in the comments. And put an example of how you tried to solve the problem so I can give you guidance.

  • as soon as I can adapt something that brings me some results I update with the examples, sorry but I haven’t been able to yet. I am trying to adapt these answers https://answall.com/a/294046/90997, https://answall.com/a/1745/90997 and https://answall.com/a/117985/90997

1 answer

2


//lê o conteúdo e transforma em array
$JSON = json_decode(file_get_contents('dados.json'), true);
//itera sobre os valores
foreach($JSON['price_usd'] as $i) {
    // inicializa os contadores
    if (!array_key_exists($i[0], $agrupados)) {
        $agrupados[$i[0]] = ['venda'=>0, 'compra'=>0];
    }
    $agrupados[$i[0]]['venda'] += $i[1];
    $agrupados[$i[0]]['compra'] += $i[2];
}

$linhaDatas = [];
$linhaVendas = [];
$linhaCompras = [];

foreach ($agrupados as $data => $valores) {
    $linhaDatas[] = $data;
    $linhaVendas[] = $valores['venda'];
    $linhaCompras[] = $valores['compra'];
}

echo implode(', ',$linhaDatas);
echo implode(', ',$linhaVendas);
echo implode(', ',$linhaCompras);
  • 1

    there are days trying, exactly what I needed!

Browser other questions tagged

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