具有相似值的数组被删除

时间:2019-03-22 04:31:47

标签: php arrays associative-array

基本上,我已经列出了关联数组,并且试图输出所有键和值。这是我的代码。

$sites = array("www.google.com" => "Google", "www.apple.com" => "Apple", 
"www.apple.com" => "Apple");
foreach ($sites as $url => $name ){
echo $name . " " . $url . "<br/>"; 
}

如您所见,“ apple”正在重复,因此没有在foreach循环中显示。这是上面代码的输出。

Google www.google.com
Apple www.apple.com

如何显示所有数组值?

谢谢。

3 个答案:

答案 0 :(得分:1)

Construct multidimensional array as follows. Because your array has duplicate indexes.
$sites = [
            ["www.google.com" => "Google"], 
            ["www.apple.com" => "Apple"], 
            ["www.apple.com" => "Apple"]
         ];

 foreach ($sites as $url_arr ){
      foreach ($url_arr as $url => $name ){
          echo $name . " " . $url . "<br/>"; 
     }
 }

答案 1 :(得分:0)

索引不能相同,希望有帮助

$sites = array(array("www.google.com" => "Google"),array( "www.apple.com" => "Apple"), 
    array("www.apple.com" => "Apple"));
    foreach ($sites as $key => $value ){

      foreach($sites[$key] as $key1 =>$value1)
        {

          echo $sites[$key][$key1] . " " . $key1 . "<br/>"; 
        }

    }

答案 2 :(得分:0)

无需使用任何for循环。

您只需要使用** array_unique()**函数即可删除重复的值。

<?php

$sites = array("www.google.com" => "Google", "www.apple.com" => "Apple", 
"www.apple.com" => "Apple");

print_r(array_unique($sites));
?>
  

输出将如下所示

Array ( [www.google.com] => Google [www.apple.com] => Apple )