Array conversion into string

2

I have the following array as I transform it into a string. This string would be used to save the products of the shopping cart in MySQL. Then they have several snacks and products:

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

Now the optional

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
    
asked by anonymous 23.09.2014 / 06:30

1 answer

6

There are several ways you can do this. Here are some possibilities:

Version 1

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

See working at IDEONE


Version 2

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

See working at IDEONE

    
23.09.2014 / 06:51