我有一个名为Array1的数组。其中包含诸如Array1 =“ John,Ali,Ali,Mark,Susan,Susan,Susan,Susan,Ali,Julie,John”之类的名称。
我想: 1st-计算每个名称在Array1中出现多少次 2-创建一个单独的数组,从Array1中删除重复项 第3个-将第二个重复计数添加到第二个数组。
因此,我的最终数组将如下所示:
Array2 =
John => 2
Ali => 3
Mark => 1
Susan => 3
Julie =>1
我将如何处理?在正确方向上的任何指针将不胜感激。 谢谢
答案 0 :(得分:1)
<?php
$array1 = ["John", "Ali", "Ali", "Mark", "Susan", "Susan", "Susan", "Ali", "Julie","John"];
print_r(array_count_values($array1));
?>
输出
Array ( [John] => 2 [Ali] => 3 [Mark] => 1 [Susan] => 3 [Julie] => 1 )
答案 1 :(得分:1)
您可以使用PHP的内置功能来实现所有这些功能:
$array = ['Susan', 'Mark', 'Susan', 'Stephan'];
计算每个名称在Array1中出现的次数
$valuesCounted = array_count_values($array);
创建一个单独的数组,从Array1中删除重复项
$unique = array_unique($array);
将重复计数添加到第二个数组。
$duplicates = array_filter($valuesCounted, function($var) {
return $var > 1;
});
$final = $unique;
$final['duplicates'] = $duplicates;
将它们放在一起:
<?php
$array = ['Susan', 'Mark', 'Susan', 'Stephan'];
$valuesCounted = array_count_values($array);
$unique = array_unique($array);
$duplicates = array_filter($valuesCounted, function($var) {
return $var > 1; // We only want to have values in our array where the value was found more than once i.e. is a duplicate.
});
$final = $unique;
$final['duplicates'] = $duplicates;
var_dump($final);
7.1.25-7.3.2的输出
array(4){ [0] => 字符串(5)“ Susan” [1] => 字符串(4)“标记” [3] => string(7)“斯蒂芬” [“重复项”] => array(1){ [“ Susan”] => 整数(2) } }
参考文献:
http://php.net/manual/en/function.array-count-values.php
答案 2 :(得分:0)
export function fetchPost(postId){
const request = axios.get(`${ROOT_URL}/posts${postId}`);
return {
type: FETCH_POST,
payload: request
};
}
进行营救:)
import { FETCH_POST } from "../actions";
export default function(state = {id: 0, title: "", infos: [{id: 0, content: "", authorId: 0}]}, action){
switch(action.type){
case FETCH_POST:
return action.payload;
}
return state;
}
答案 3 :(得分:0)
以上所有问题的完整说明
<?php
$testArray = [
'foo',
'bar',
'beer',
'coffee',
'foo',
'bar',
'beer',
'coffee',
'foo',
'bar',
'beer',
'coffee',
];
$countArray = count($testArray);
$duplicatesRemoved = array_unique($testArray);
$vals = array_count_values($testArray);
print_r($vals);
答案 4 :(得分:0)
检查array_count_value函数。它将非常适合您。检查以下代码:
$collection = array("Geeks", "for", "Geeks", "Geeks", "Welcome", "for");
$collectionValCounter = array_count_values($collection); // This will print all values with their apperance counter.
$collectionUnique = array_values(array_flip($collectionValCounter)); //Unique values with reset keys.
print_r($collectionValCounter);
print_r($collectionUnique);
希望它对您有帮助。
答案 5 :(得分:0)
这样的事情会做我想做的事情:
$array2 = array();
foreach {$array1 as $name}{
if (array_key_exists($name, $array2)) {
$array2[$name] = $array2[$name] + 1;
} else {
$array2[$name] = 1;
}
}
问候,凯
答案 6 :(得分:0)
只需使用内置的PHP函数
array_count_values()
例如
$array1 = array('john','john', 'Ali');
$array2 = array_count_values($array);
print_r($array2);
结果:
Array ( [john] => 2 [Ali] => 1 )