Assigning a value to each array element PHP

2020-03-25 11:23发布

问题:

Say you have an array like this...

username, password, email

and you need to assign a value to each element. After, this needs to be formatted into a string like this:

username=someRandomValueAssigned&password=someRandomValueAssigned&email=someRandomValueAssigned

how would I do this? Thanks.

回答1:

$keys = array('username', 'password', 'email');

$values = array('someusername', 'somepassword', 'someemail');

$data = array_combine($keys, $values);

array_combine will return an associative array like,

$data = array( 
          'username' => 'someusername',
          'password' => 'somepassword',
          'email' => 'someemail'
        );

then the result you want can be achieved using a simple foreach loop

$str = '';

foreach($data as $k=>$v) {
   $str .= $k > 0 ? '&' : '';
   $str .= $k . '=' . $v ;
}

echo $str;

Also, I suspect you are trying to build a url so you might want to check out php's http_build_query function



回答2:

$array_value=array();
$array_value['username']=somevalue;
$array_value['password']=somevalue;
$array_value['email']=somevalue;
$array_str=array();
foreach($array_value as $key=>$value){
   array_push($array_str,$key."=".$array_value[$value]);
}
$array_str=join("&",$array_str);
echo $array_str;


回答3:

Looks like you're building a query string, I think you want to use http_build_query():

$data = array(
    'username'  =>  'someRandomValueAssigned',
    'password'  =>  'someRandomValueAssigned',
    'email'     =>  'someRandomValueAssigned',
);

$query_string = http_build_query($data);

This should give you the result you're looking for.

http_build_query — Generate URL-encoded query string

http://php.net/manual/function.http-build-query.php



回答4:

$randomValue = array('username' => 'someValue' ); // same for other
foreach($array as &$value){
  $value = $value.'='.$randomValue[$value];
}

echo implode('&', $array);