String array conversion

Asked

Viewed 136 times

3

I have the following array as I turn it into a string. This string would be used to save the products from the shopping cart in Mysql. So they have various snacks and products:

products 5,2,5 use that code implode(',', $adicional);

now the options

8#-2:7#-1,8#-2:7#-1,8#-2:7#-1

each, and a snack and its optional

array
(
    [8] => -2
    [7] => -1
)

string: 8#-2:7#-1 // preciso da string de esse formato

1 answer

6


There are several ways to do this. Here are some possibilities:

Version 1

$saida = '';
$cola = '';
foreach( $minhaarray as $chave => $valor ) {
   $saida .= $cola.$chave.'#'.$valor;
   $cola=':';
}

See working on IDEONE


Version 2

$saida = implode(
   ':',
   array_map(
      function( $valor, $chave ) { return $chave.'#'.$valor; },
      $minhaarray,
      array_keys( $minhaarray )
   )
);

See working on IDEONE

  • perfect :Thank you very much Bacco

Browser other questions tagged

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