将数组与foreach相结合

时间:2012-11-14 00:18:26

标签: php arrays foreach

要检查数组中相等值的频率,请使用以下方法计算:

$count = array_count_values($array_names);

要获取每个键/值对,我使用此foreach循环:

foreach ($count as $key => $value) {
    echo $value . '–' . $key . '<br />'; 
}

可能的输出:

2 – Harry Peters
1 – Winston Meyers
3 – Jason Williams

现在我有了第二个带URL的数组:

$urls = array(http://harry-peters.com, http://winston-meyers.com, http://jason-williams.com);

该数组应该包含在$key变量中,如

echo $value . '- <a href="' . $url . '">' . $key . '</a><br />'; 

所以我会得到类似的东西:

2 – <a href="http://harry-peters.com">Harry Peters</a>
1 – <a href="http://winston-meyers.com">Winston Meyers</a>
3 – <a href="http://jason-williams.com">Jason Williams</a>

但我不知道如何为第一个循环的URL实现另一个foreach循环。

2 个答案:

答案 0 :(得分:0)

  $count =array("mark Ortiz", "You", "me", "hello");
  $urls = array("http://harry-peters.com", "http://winston-meyers.com", "http://jason-williams.com")
    foreach ($count as $key => $value) {
    //echo $key . '-' . $value . '<br />'; 
    $count[$key] = "<a href='$urls[$key]' >".$value."</a>";// this forced value to be formatted
    }
    foreach ($count as $key => $value) {
    echo $key . '-' . $value . '<br />'; 

    }

应该很容易,我希望你小心,如果要避免数组索引超出绑定异常

答案 1 :(得分:0)

这对你有用吗?

<?php

$names = array
(
    2 => "Harry Peters",
    1 => "Winston Meyers",
    3 => "Jason Williams"
);

$urls = array
(
    "http://harry-peters.com", 
    "http://winston-meyers.com", 
    "http://jason-williams.com"
);

$counter = 0;

foreach ($names as $key => $value)
{
    echo $key . '- <a href="' . $urls[$counter] . '">' . $value . '</a><br />';

    $counter++;
}

要小心,因为网址必须与名称的顺序完全匹配。