简体   繁体   English

为每个数组元素PHP赋值

[英]Assigning a value to each array element PHP

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. 谢谢。

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

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

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

array_combine will return an associative array like, array_combine将返回一个关联数组,如

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

then the result you want can be achieved using a simple foreach loop 那么你想要的结果可以用一个简单的foreach循环来实现

$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 此外,我怀疑你正在尝试建立一个网址,所以你可能想看看php的http_build_query函数

$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;

Looks like you're building a query string, I think you want to use http_build_query() : 看起来你正在构建一个查询字符串,我想你想使用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_build_query - 生成URL编码的查询字符串

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

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

echo implode('&', $array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM