Separate Array into groups and insert them into a pre-defined text

Asked

Viewed 43 times

0

I get a string in format:

[name, Qtd, price, name, Qtd, price...].

Ex: [Tomato Sauce, 12, 4.59, Popcorn, 5, 7.90...]

I want to separate every 3 commas an element and separate each element into 3 more subelements.

Ex: $pedido[i] = $subelemento_nome, $subelemento_qtd, $subelemento_preco;

$subelemento_nome[i];
$subelemento_qtd[i];
$subelemento_preco[i];

And for each element to return something like this:

$pedido[i] = "<p>".$subelemento_qtd[i]."x ". $subelemento_nome[i]." - R$ ".$subelemento_preco[i]."</p><br>";

Return:

<p>12x Molho de Tomate - R$ 4.59</p><br>
<p>5x Pipoca - 7.90</p><br>...

At the end of everything I will send the string $request to my database.

1 answer

1


You can remove the brackets and separate all values by comma:

$texto = '[Molho de Tomate, 12, 4.59, Pipoca, 5, 7.90]';
$valores = explode(',', trim($texto, '[]'));

So you’ll have something like:

Array
(
    [0] => Molho de Tomate
    [1] =>  12
    [2] =>  4.59
    [3] =>  Pipoca
    [4] =>  5
    [5] =>  7.90
)

To take every three values, use the array_chunk:

$produtos = array_chunk($valores, 3);

Getting:

Array
(
    [0] => Array
        (
            [0] => Molho de Tomate
            [1] =>  12
            [2] =>  4.59
        )

    [1] => Array
        (
            [0] =>  Pipoca
            [1] =>  5
            [2] =>  7.90
        )

)

Then just go through this list $produtos and do as you wish.

For example:

$texto = '[Molho de Tomate, 12, 4.59, Pipoca, 5, 7.90]';
$valores = explode(',', trim($texto, '[]'));
$produtos = array_chunk($valores, 3);

foreach ($produtos as $produto) {
    list($nome, $qtd, $preco) = array_map('trim', $produto);

    $preco = number_format($preco, 2, ',', '');

    echo "<p>{$qtd}x {$nome} - R$ {$preco}</p>", PHP_EOL;
}

The exit will be:

<p>12x Molho de Tomate - R$ 4,59</p>
<p>5x Pipoca - R$ 7,90</p>
  • Very good, exactly as I wanted. You know tell me pq echo shows the output as expected but when I pass to my database only the last item is saved?

  • Your example, for example, saves to db only <p>5x Pipoca - R$ 7,90</p>

  • Why you must have done wrong :D hehehe Maybe you are storing in variables and only saving in the bank outside the loop repetition, then you will save only the current values of the variables (but it is only speculation).

  • I get it... how do I store all the results in a variable to be recorded at once? If I put the mysql part in the loop, each value is saved individually.

  • I got :D, did some research and found the solution. I added$pedido_conteudo = "<p>{$qtd}x {$nome} - R$ {$preco}</p>\n"; and $conteudo .=$pedido_conteudo; inside the loop, and outside the loop is the mysql part saving $content

Browser other questions tagged

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