在面试中我被问到一个问题。以下是问题:
$arry= array("1"=>"20", "2"=>"20", "3"=>"30", "4"=>"40" "5"=>"20");
我被要求通过使用foreach循环找到具有相同值的键。
我仍然不知道这个问题的解决方案。任何帮助??
答案 0 :(得分:5)
$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);
答案 1 :(得分:2)
<?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);
答案 2 :(得分:1)
$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)
答案 3 :(得分:0)
foreach ($arry as $key=>$value) {
if ($value == $findValue)
print $key.' ';
}
示例$findValue
为20,然后此代码打印1 2 5
答案 4 :(得分:0)
最简单的方法:
<?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);
?>
试一试here