php 如何将数组传递给函数,并用数组返回结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2158848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an array into a function, and return the results with an array
提问by JoeCortopassi
So I'm trying to learn how to pass arrays through a function, so that I can get around PHP's inability to return multiple values. Haven't been able to get anything to work so far, but here is my best try. Can anybody point out where I'm going wrong?
所以我正在尝试学习如何通过函数传递数组,以便我可以解决 PHP 无法返回多个值的问题。到目前为止还没有任何东西可以工作,但这是我最好的尝试。有人能指出我哪里出错了吗?
function foo($array)
{
$array[3]=$array[0]+$array[1]+$array[2];
return $array;
}
$waffles[0]=1;
$waffles[1]=2;
$waffles[2]=3;
foo($waffles);
echo $waffles[3];
For clarification: I want to be able to pass multiple variables into a function, do something, then return multiple variables back out while keeping them seperate. This was just an example I was trying to get working as a work around for not being able to return multiple variables from an array
澄清一下:我希望能够将多个变量传递给一个函数,做一些事情,然后将多个变量返回,同时保持它们分开。这只是一个示例,我试图解决无法从数组中返回多个变量的问题
回答by SoapBox
You seem to be looking for pass-by-reference, to do that make your function look this way (note the ampersand):
您似乎正在寻找传递引用,这样做使您的函数看起来像这样(注意&符号):
function foo(&$array)
{
$array[3]=$array[0]+$array[1]+$array[2];
}
Alternately, you can assign the return value of the function to a variable:
或者,您可以将函数的返回值分配给变量:
function foo($array)
{
$array[3]=$array[0]+$array[1]+$array[2];
return $array;
}
$waffles = foo($waffles)
回答by Tor Valamo
You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)
您通过复制将数组传递给函数。PHP 中只有对象通过引用传递,数组不是对象。这就是你所做的(注意 &)
function foo(&$arr) { # note the &
$arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6
That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?
除此之外,我不确定您为什么要进行那样的特定操作。为什么不直接返回总和而不是将其分配给新的数组元素?
回答by user2587105
function foo(Array $array)
{
return $array;
}
回答by matpie
I always return multiple values by using a combination of list()and array()s:
我总是使用list()和array()s的组合返回多个值:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
您可以随意命名它们。我选择保持函数变量和返回变量相同以保持一致性,但您可以随意调用它们。
See list()for more information.
有关list()更多信息,请参阅。
回答by Gordon
Try
尝试
$waffles = foo($waffles);
Or pass the array by reference, like suggested in the other answers.
或者通过引用传递数组,就像其他答案中建议的那样。
In addition, you can add new elements to an array without writing the index, e.g.
此外,您可以在不写入索引的情况下向数组添加新元素,例如
$waffles = array(1,2,3); // filling on initialization
or
或者
$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;
On a sidenote, if you want to sum all values in an array, use array_sum()
在旁注中,如果您想对数组中的所有值求和,请使用 array_sum()
回答by streetparade
i know a Class is a bit the overkill
我知道 Class 有点矫枉过正
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
回答by Tyler Carter
You are not able to return 'multiple values' in PHP. You can return a single value, which might be an array.
您无法在 PHP 中返回“多个值”。您可以返回单个值,它可能是一个数组。
function foo($test1, $test2, $test3)
{
return array($test1, $test2, $test3);
}
$test1 = "1";
$test2 = "2";
$test3 = "3";
$arr = foo($test1, $test2, $test3);
$test1 = $arr[0];
$test2 = $arr[1];
$test3 = $arr[2];
回答by Gautam Sharma
Here is how I do it. This way I can actually get a function to simulate returning multiple values;
这是我如何做到的。这样我实际上可以得到一个函数来模拟返回多个值;
function foo($array)
{
foreach($array as $_key => $_value)
{
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
/* Set the variables to pass to function, in an Array */
$waffles['variable1'] = "value1";
$waffles['variable2'] = "value2";
$waffles['variable3'] = "value3";
/* Call Function */
parse_str( foo( $waffles ));
/* Function returns multiple variable/value pairs */
echo $variable1 ."<br>";
echo $variable2 ."<br>";
echo $variable3 ."<br>";
Especially usefull if you want, for example all fields in a databaseto be returned as variables, named the same as the database table fields. See 'db_fields( )' function below.
如果您希望,例如,数据库中的所有字段都作为变量返回,命名与数据库表fields相同,则特别有用。请参阅下面的“ db_fields()”函数。
For example, if you have a query
例如,如果您有一个查询
select login, password, email from members_table where id = $idFunction returns multiple variables:
函数返回多个变量:
$login, $password and $emailHere is the function:
这是函数:
function db_fields($field, $filter, $filter_by, $table = 'members_table') {
/*
This function will return as variable names, all fields that you request,
and the field values assigned to the variables as variable values.
$filter_by = TABLE FIELD TO FILTER RESULTS BY
$filter = VALUE TO FILTER BY
$table = TABLE TO RUN QUERY AGAINST
Returns single string value or ARRAY, based on whether user requests single
field or multiple fields.
We return all fields as variable names. If multiple rows
are returned, check is_array($return_field); If > 0, it contains multiple rows.
In that case, simply run parse_str($return_value) for each Array Item.
*/
$field = ($field == "*") ? "*,*" : $field;
$fields = explode(",",$field);
$assoc_array = ( count($fields) > 0 ) ? 1 : 0;
if (!$assoc_array) {
$result = mysql_fetch_assoc(mysql_query("select $field from $table where $filter_by = '$filter'"));
return ${$field} = $result[$field];
}
else
{
$query = mysql_query("select $field from $table where $filter_by = '$filter'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $_key => $_value) {
$str .= "{$_key}=".$_value.'&';
}
return $str = substr($str, 0, -1);
}
}
}
Below is a sample call to function. So, If we need to get User Data for say $user_id = 12345, from the members table with fields ID, LOGIN, PASSWORD, EMAIL:
下面是对函数的示例调用。因此,如果我们需要从包含字段 ID、登录、密码、电子邮件的成员表中获取 $user_id = 12345 的用户数据:
$filter = $user_id;
$filter_by = "ID";
$table_name = "members_table"
parse_str(db_fields('LOGIN, PASSWORD, EMAIL', $filter, $filter_by, $table_name));
/* This will return the following variables: */
echo $LOGIN ."<br>";
echo $PASSWORD ."<br>";
echo $EMAIL ."<br>";
We could also call like this:
我们也可以这样调用:
parse_str(db_fields('*', $filter, $filter_by, $table_name));
The above call would return all fields as variable names.
上面的调用会将所有字段作为变量名返回。
回答by Hello Hack
Another way is:
另一种方式是:
$NAME = "John";
$EMAIL = "[email protected]";
$USERNAME = "John123";
$PASSWORD = "1234";
$array = Array ("$NAME","$EMAIL","$USERNAME","$PASSWORD");
function getAndReturn (Array $array){
return $array;
}
print_r(getAndReturn($array));

