String concatenation in PHP from Array

Asked

Viewed 2,330 times

-1

I have a query to my database that returns to me an array each database row is an array,

$qr = DBRead('sales', "WHERE status = 1");
foreach ($qr as $position => $linha){
    $vendas = $linha['cod_produto'];

    var_dump($vendas); 
}

This I printed for the sequinte array

array (size=25)
    'venda' => string '96' (length=2)
    'cod_produto' => string '1; 2; 8' (length=7)

array (size=25)
    'venda' => string '98' (length=2)
    'cod_produto' => string '; 1; 2; 8' (length=9)

And so on, the more I register the more arrays.

My question is I want to get the key cod_produto and selects its value and put in a single string with all these values concatenated someone has an idea of how to do this with php?

  • Use the Join or implode function. It is simpler and more elegant. function Join: https://www.php.net/manual/en/function.join.php implode function: https://www.php.net/manual/en/function.implode.php

1 answer

0

To concatenate string in php you must use $vartexto = $vartexto . 'texto novo'; or in a reduced form $vartexto.='texto novo';

Follow your code snippet with a variable $cod_produtos_juntos that will make this concatenation for you:

$qr = DBRead('sales', "WHERE status = 1");

$cod_produtos_juntos = '';
foreach ($qr as $position => $linha)
{
    $cod_produtos_juntos.=$linha['cod_produto'];
}

echo $cod_produtos_juntos;
  • 1

    What was confusing to me is that he attributed to $vendas$ the value of $linha['cod_produto'] and when did the var_dump, $vendas has again the index cod_produto. By the logic presented would be $cod_produtos_juntos .= $vendas['cod_produto']. Although I believe he got mixed up in the same result.

  • What you said makes perfect sense Anderson.

  • If $sales['cod_product'] is an array with sale and cod_product, then to get only cod_product would have to be $cod_products_together.= $line['cod_product']['cod_product']; but I believe Joao has var_dump into $pure line before.

  • Antonio, if you want to add your answer so there is no need to create another one: https://repl.it/F6BG/0. So you can see the difference in operation.

  • I could not open your link. Hangs my Firefox. :/

Browser other questions tagged

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