Extract key pair / value from a querystring

2

I have this code where I get the value of a post and ajax.

 $string = 'nome=Alexandre+Sousa&cpf=0000000000000&email=sousa.akira%40gmail.com&site=www.uniaomaker.com.br';

$dados = explode('&',$string);
$total = count($dados);
$array = '';
foreach ($dados as $list) {
    $vals = explode('=',$list);
    $array .= '"'.$vals[0].'"'. '=>'.'"'.$vals[1].'"'.',';
}

$keys = array($array);

echo '<pre>';
print_r($keys);

The result I get is the following

  

Array (       [0] = > "name" => "Alexandre + Sousa", "cpf" = > "0000000000000", "email" => "sousa.akira% 40gmail.com", "site" => "www.uniaomaker.com .br ",   )

But I need the array to return this way

  

Array (       [name] = > Alexandre + Sousa       [cpf] = > 0000000000000       [email] = > sousa.akira% 40gmail.com       [site] = > www.uniaomaker.com.br)

I've tried many more tips and I have not found a solution,

    
asked by anonymous 15.08.2015 / 06:02

2 answers

1

If you need to transform this querystring into an array use the parse_str () function for this :

<?php

$str = "nome=Alexandre+Sousa&cpf=0000000000000&email=sousa.akira%40gmail.com&site=www.uniaomaker.com.br";
parse_str($str, $valores);

print_r($valores);

Output:

Array
(
    [nome] => Alexandre Sousa
    [cpf] => 0000000000000
    [email] => [email protected]
    [site] => www.uniaomaker.com.br
)

Example - ideone

    
15.08.2015 / 06:23
2

It is more practical using the parse_str() function because of the format of the string.

However, the original script was almost there. It was enough to fill an associative array instead of concatenating the data as a common variable.

 $string = 'nome=Alexandre+Sousa&cpf=0000000000000&email=sousa.akira%40gmail.com&site=www.uniaomaker.com.br';

$dados = explode('&',$string);
$total = count($dados);
$array = '';
foreach ($dados as $list) {
    $vals = explode('=',$list);
    $array[$vals[0]] = $vals[1];
}

echo '<pre>';
print_r($array);
    
15.08.2015 / 09:04