从数组中获取重复键
Get duplicate keys from array
我有一个如下所示的数组,我需要检测所有重复的键,而不是值。
$array1 = array(
"a" => "Mike",
"b" => "Charles",
"b" => "Robert",
"c" => "Joseph"
);
我使用的所有函数都专注于值,如果我应用 flip_array(),它会自动删除重复的键。
Array-密钥永远不会重复,因为它们是唯一标识符。 (如数据库主键)
声明 $array['b']
两次将导致覆盖第一个值。
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
按照您的逻辑 print_r($array1['b'])
会输出 2 个值,这是不可能的。
如果您想要一个键的多个值,请添加一个维度:
$array1 = array(
"a" => "Mike",
"b" => array(1 => "Charles", 2 => "Robert"),
"c" => "Joseph"
);
print_r($array1['b']);
将return
Array ( [1] => Charles [2] => Robert )
编辑
如果没有办法,你必须使用正则表达式 preg_match 和你的数组作为字符串:
$array1 =' array(
"a" => "Mike",
"b" => "Charles",
"b" => "Robert",
"c" => "Joseph"
)';
preg_match_all('/([A-Z])\w+/', $array1, $matches);
print_r($matches[0]);
将return
Array ( [0] => Mike [1] => Charles [2] => Robert [3] => Joseph )
使用@TechTreeDev 提供的答案,这是我用来显示数组中的重复键和值的函数。 Working demo at IDEOne.
参数textOfArray()
将是简单引号上的数组内容。
function findCoincidences($textOfArray) {
$output = "";
// Locate all the duplicated Strings (keys and values)
preg_match_all('/".*?"/', $textOfArray, $matches);
// Make array where key = string, and value = repetitions
$arrayCoinc = array_count_values($matches[0]);
$output = "==== COINCIDENCES ====<br>";
foreach ($arrayCoinc as $k => $v){
if ($v > 1){
$output .= "<b>".$k."</b> Found:".$v."<br>";
}
}
return $output;
}
echo findCoincidences($array1);
结果:
==== COINCIDENCES ====
"a" Found:4
"f" Found:3
"e" Found:3
我有一个如下所示的数组,我需要检测所有重复的键,而不是值。
$array1 = array(
"a" => "Mike",
"b" => "Charles",
"b" => "Robert",
"c" => "Joseph"
);
我使用的所有函数都专注于值,如果我应用 flip_array(),它会自动删除重复的键。
Array-密钥永远不会重复,因为它们是唯一标识符。 (如数据库主键)
声明 $array['b']
两次将导致覆盖第一个值。
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
按照您的逻辑 print_r($array1['b'])
会输出 2 个值,这是不可能的。
如果您想要一个键的多个值,请添加一个维度:
$array1 = array(
"a" => "Mike",
"b" => array(1 => "Charles", 2 => "Robert"),
"c" => "Joseph"
);
print_r($array1['b']);
将return
Array ( [1] => Charles [2] => Robert )
编辑
如果没有办法,你必须使用正则表达式 preg_match 和你的数组作为字符串:
$array1 =' array(
"a" => "Mike",
"b" => "Charles",
"b" => "Robert",
"c" => "Joseph"
)';
preg_match_all('/([A-Z])\w+/', $array1, $matches);
print_r($matches[0]);
将return
Array ( [0] => Mike [1] => Charles [2] => Robert [3] => Joseph )
使用@TechTreeDev 提供的答案,这是我用来显示数组中的重复键和值的函数。 Working demo at IDEOne.
参数textOfArray()
将是简单引号上的数组内容。
function findCoincidences($textOfArray) {
$output = "";
// Locate all the duplicated Strings (keys and values)
preg_match_all('/".*?"/', $textOfArray, $matches);
// Make array where key = string, and value = repetitions
$arrayCoinc = array_count_values($matches[0]);
$output = "==== COINCIDENCES ====<br>";
foreach ($arrayCoinc as $k => $v){
if ($v > 1){
$output .= "<b>".$k."</b> Found:".$v."<br>";
}
}
return $output;
}
echo findCoincidences($array1);
结果:
==== COINCIDENCES ====
"a" Found:4
"f" Found:3
"e" Found:3