Extract key/value pair from querystring

Asked

Viewed 131 times

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 and 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 have tried many tips but could not find solution,

  • 1

    You are returning an array within another array, to return what you need, you should return each element as a position of the array

  • could give me a hand with the code?

2 answers

2

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

However, the original script was almost there.. Just 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);

1


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

<?php

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

print_r($valores);

Exit:

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

Example - ideone

Browser other questions tagged

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