array in a php foreach

Asked

Viewed 1,090 times

0

I’ll try to be objective in doubt:

I have the following code:

<?php

foreach ($modelo as $k => $v) {
    $sql_ = "SELECT * FROM pedido WHERE modelo LIKE '%".$v."%' ORDER BY id ASC";
    $disp_sql_ = $mysqli->query($sql_);

    while ($data_ = $disp_sql_->fetch_array()) { 
        $quantidade_    += ($data_['total'] * $data_['kit']);
    }
}

The total of the variable $quantidade, has the sum output of all models.

In the database it’s like this:

valor 1 = 20 ($modelo 1)
valor 2 = 30 ($modelo 1)
valor 3 = 50 ($modelo 1)
valor 4 = 50 ($modelo 2)
valor 5 = 50 ($modelo 2)

The variable $quantidade brings me this:

$quantidade = 200;

What I would like you to bring me the result as follows:

$quantidade = array([0] => 100, [2] => 100)

a sum to each model change (each foreach change), results in an array.

  • starts the $quantity before the while $quantidade_ = array(); while (){ $quantidade_ = array( //seucaldulo ) }

3 answers

4


You can simply separate the values in the array within your for as follows:

<?php

$quantidade = [];

foreach ($modelo as $k => $v) {
    $sql_ = "SELECT * FROM pedido WHERE modelo LIKE '%".$v."%' ORDER BY id ASC";
    $disp_sql_ = $mysqli->query($sql_);

    while ($data_ = $disp_sql_->fetch_array()) { 
        // Se a chave não existir cria uma nova com o valor 0
        $quantidade[$data_['id_modelo']] = $quantidade[$data_['id_modelo']] ?? 0;

        // Soma normalmente
        $quantidade[$data_['id_modelo']] += $data_['total'] * $data_['kit'];
    }
}

However, a better way would be to do these calculations in the database, using the function SUM() along with GROUP BY. Example:

<?php

$quantidade = [];

foreach ($modelo as $k => $v) {
    $sql_ = <<<SQL
        SELECT 
            id_modelo,
            SUM(total * kit) as soma
        FROM pedido 
        WHERE modelo LIKE '%$v%'
        GROUP BY id_modelo,
        ORDER BY id ASC;
SQL;
    $disp_sql_ = $mysqli->query($sql_);

    while ($data_ = $disp_sql_->fetch_array()) { 
        // Já retorna o somatório do banco de dados
        $quantidade[$data_['id_modelo']] = $data_['soma']];
    }
}
  • thanks Fernando, I managed to make the account already in the bank consultation, thanks even!

  • I’m glad it worked out!

0

You can initialize the amount out of the loop

<?php
$quantidade_ = array();
foreach ($modelo as $k => $v) {
    $sql_ = "SELECT * FROM pedido WHERE modelo LIKE '%".$v."%' GROUP BY id ASC";
    $disp_sql_ = $mysqli->query($sql_);

    while ($data_ = $disp_sql_->fetch_array()) { 
        $quantidade_[] =  array(
               ($data_['total'] * $data_['kit']);
           )
    }
}

Or initialize like this:

 $quantidade_ = []

and thus feed:

 $quantidade[] =  ($data_['total'] * $data_['kit']);

0

A simple way to solve this:

<?php

foreach ( $modelo as $k => $v ) {
    $sql_      = "SELECT * FROM pedido WHERE modelo LIKE '%".$v."%' ORDER BY id ASC";
    $disp_sql_ = $mysqli->query( $sql_ );

    $ultimo_valor = 0;
    while ( $data_ = $disp_sql_->fetch_array() ) { 
        $quantidade_[$k] = $ultimo_valor + ( $data_['total'] * $data_['kit'] );
        $ultimo_valor   += ( $data_['total'] * $data_['kit'] );
    }
}

Print out what it looks like:

Array
(
    [0] => 20
    [1] => 50
    [2] => 100
    [3] => 150
    [4] => 200
)
  • Kayo the AP needs to sum up grouped by model, its solution makes an accumulated sum. I don’t think that’s what he wants.

  • He’s a friend, I put the answer but with some doubts if that’s what he needed.

  • 1

    So we’re waiting for him to comment here. D At worst it’s not, but it might be helpful.

  • 1

    Kayo e Fernando, yes, I had tried this way and he brings the accumulated sum, did not solve me, I thought in a thousand forms but without success, I decided to post here to see if someone can save me, thanks for the help

Browser other questions tagged

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