通过第二个数组循环数组

时间:2010-07-26 19:55:27

标签: php arrays foreach

寻找循环遍历一系列URL并将每个关键字从第二个数组注入到每个URL中,但无法理解数组。例如:

$key = array("Keyword+1", "Keyword+2", "Keyword+3"),
$url =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p="),

我想输出以上内容:

  

google.co.uk/#hl=en&q=Keyword+1
  google.co.uk/#hl=en&q=Keyword+2
  google.co.uk/#hl=en&q=Keyword+3
  bing.com/search?q=Keyword+1
  bing.com/search?q=Keyword+2
  bing.com/search?q=Keyword+3
  uk.search.yahoo.com/search?vc=&p=Keyword+1
  uk.search.yahoo.com/search?vc=&p=Keyword+2
  uk.search.yahoo.com/search?vc=&p=Keyword+3

有没有一种有效的方法来实现这一目标? :)

4 个答案:

答案 0 :(得分:2)

foreach($url as $currenturl)
{
    foreach($key as $currentkey)
    {
        echo $currenturl . $currentkey . '\n';
    }
}

试试这个

答案 1 :(得分:0)

您首先想要遍历$url数组,然后对于$url数组中的每个项目,您还想循环遍历$key数组中的所有键并附加它们您从$url

中选择的项目
foreach ($url as $u)
{
    foreach ($key as $k)
    {
        echo $u.$k."\n";
    }
}

答案 2 :(得分:0)

以下是如何做到这一点:

$keys = array("Keyword+1", "Keyword+2", "Keyword+3");
$urls =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p=");

$my_array = array();

foreach($urls as $url)
{
    foreach($keys as $key)
    {
        $my_array[] = $url . $key;
    }
}

print_r($my_array);

<强>结果:

Array
(
    [0] => google.co.uk/#hl=en&q=Keyword+1
    [1] => google.co.uk/#hl=en&q=Keyword+2
    [2] => google.co.uk/#hl=en&q=Keyword+3
    [3] => bing.com/search?q=Keyword+1
    [4] => bing.com/search?q=Keyword+2
    [5] => bing.com/search?q=Keyword+3
    [6] => uk.search.yahoo.com/search?vc=&p=Keyword+1
    [7] => uk.search.yahoo.com/search?vc=&p=Keyword+2
    [8] => uk.search.yahoo.com/search?vc=&p=Keyword+3
)

答案 3 :(得分:0)

您所描述的是对外部产品的概括。

为此定义更高阶函数会更有趣:

/**
 * A generalization of the  outer product, forming all the possible
 * combinations of the elements of the two arrays and feeding them
 * to $f.
 * The keys are disregarded
 **/
function array_outer($f, array $array1, array $array2) {
    $res = array();
    foreach ($array1 as $e1) {
        $cur = array();
        foreach ($array2 as $e2) {
            $cur[] = $f($e1, $e2);
        }
        $res[] = $cur;
    }
    return $res;
}

$f = function ($a,$b) { return $a.$b; };
print_r(array_outer($f, array("a","b","c"), array("1", "2", "3")));

给出:

Array
(
    [0] => Array
        (
            [0] => a1
            [1] => a2
            [2] => a3
        )

    [1] => Array
        (
            [0] => b1
            [1] => b2
            [2] => b3
        )

    [2] => Array
        (
            [0] => c1
            [1] => c2
            [2] => c3
        )

)

见Mathematica的Outer