有一次我在一次采访中被问到一个问题。下面是问题:
$arry= array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40" "5"=>"20");
我被要求通过使用 foreach 循环找到具有相同值的键。
我仍然不知道这个问题的解决方案。有什么帮助吗??
$arry= array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40", "5"=>"20");
$results = array();
foreach($arry as $key=>$value) {
$results[$value][] = $key;
}
var_dump($results);
<?php
$arry= array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40","5"=>"20");
$list = array();
foreach ($arry as $key => $value)
{
if (!isset($list[$value]))
{
$list[$value] = array();
}
$list[$value][] = $key;
}
var_export($list);
$arry= array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40", "5"=>"20");
$newArr = array();
foreach($arry as $key => $val) {
if(!array_key_exists($val, $newArr)) $newArr[$val] = "";
$newArr[$val] .= " - " . $key;
}
var_dump($newArr);
输出:VALUES => KEYS_WITH_SAME_VALUES
array (size=3)
20 => string ' - 1 - 2 - 5' (length=12)
30 => string ' - 3' (length=4)
40 => string ' - 4' (length=4)
foreach ($arry as $key=>$value) {
if ($value == $findValue)
print $key.' ';
}
示例$findValue
为 20,则此代码打印1 2 5
最简单的方法:
<?php
$array = array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40" ,"5"=>"20");
print_r(array_count_values($array));
?>
使用 foreach :
<?php
$array = array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40" ,"5"=>"20");
$result = array();
foreach($array as $value) {
$result[$value]++;
}
print_r($result);
?>
在这里试一试