0

Possible Duplicate:
foreach with three variables add

I'm new to PHP so bear with me.

I have a url with two variables like so:

 ?foo=1,2,3,4&bar=a,b,c,d

Both parameters will always have the same amount of elements. I need to loop through the amount of elements like so:

1a
2b
3c
4d

and on each iteration assign two variables for foo and bar value.

If this was javascript no problem, but I have no idea how to do this PHP. This is what I have:

$foo = strtok($rvar_foo,",");
$bar = strtok($rvar_bar,",");
while ( $foo ){
  # now how do I get the corresponding value for $bar?
}
4

3 回答 3

4
$foo = isset($_GET['foo']) ?  explode(",", $_GET['foo']) :  array();
$bar = isset($_GET['bar']) ?  explode(",", $_GET['bar']) :  array();

for ($i = 0; $i < count($foo); $i++) {
    echo $foo[$i] . $bar[$i] . "<br />";
}

Is this what you want?

Output

1a
2b
3c
4d
于 2012-10-08T21:01:01.427 回答
3

Use array_map:

function my_function($a, $b)
{

    var_dump($a . $b );
    // Do something with both values.
    // The first parameter comes from the first array, etc.
}

array_map("my_function", explode(",",$_GET['a']), explode(",",$_GET['b']));
于 2012-10-08T21:18:56.823 回答
1

Maybe you are looking for array_combine. It creates an array from two arrays, using one array for the keys, the other array for the values.

$foo = explode(',', $_GET['foo']);
$bar = explode(',', $_GET['bar']);
$foobar = array_combine($foo, $bar);

This would result in $foobar using the values from $foo as its keys and $bar for the values.

Calling print $foobar[1] would result in a being printed to the output. (You can find a running example here)

于 2012-10-08T21:07:04.980 回答