删除具有相似值的数组
Array with similar value being removed
基本上,我有一个关联数组列表,我正在尝试为所有数组输出键和值。这是我的代码。
$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
如何显示所有数组值?
谢谢。
索引不能相同,希望对您有所帮助
$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/>";
}
}
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/>";
}
}
无需使用任何for循环。
您只需要使用 **array_unique()**
函数来删除重复值。
<?php
$sites = array("www.google.com" => "Google", "www.apple.com" => "Apple",
"www.apple.com" => "Apple");
print_r(array_unique($sites));
?>
Output will be like following
Array ( [www.google.com] => Google [www.apple.com] => Apple )
基本上,我有一个关联数组列表,我正在尝试为所有数组输出键和值。这是我的代码。
$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
如何显示所有数组值?
谢谢。
索引不能相同,希望对您有所帮助
$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/>";
}
}
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/>";
}
}
无需使用任何for循环。
您只需要使用 **array_unique()**
函数来删除重复值。
<?php
$sites = array("www.google.com" => "Google", "www.apple.com" => "Apple",
"www.apple.com" => "Apple");
print_r(array_unique($sites));
?>
Output will be like following
Array ( [www.google.com] => Google [www.apple.com] => Apple )