Php 如何查找以前在多数组中找到的值
我目前确实有以下问题。我必须检查数组是否包含完全相同的值,以及之前是否找到了这些值 int(3)以前未找到,因此为0, int(8)以前未找到,因此为0, int(5)以前未找到,因此为0, int(8)是以前发现的,所以它是1, int(3)和int(8)没有一起找到,所以它是0,依此类推 我已经用array_unique试过了,但没有达到我想要的效果 例如:Php 如何查找以前在多数组中找到的值,php,arrays,find,unique,Php,Arrays,Find,Unique,我目前确实有以下问题。我必须检查数组是否包含完全相同的值,以及之前是否找到了这些值 int(3)以前未找到,因此为0, int(8)以前未找到,因此为0, int(5)以前未找到,因此为0, int(8)是以前发现的,所以它是1, int(3)和int(8)没有一起找到,所以它是0,依此类推 我已经用array_unique试过了,但没有达到我想要的效果 例如: array(7) { [2] => array(1) { [0] => int(3) } [3] =&
array(7) {
[2] => array(1) {
[0] => int(3)
}
[3] => array(1) {
[0] => int(8)
}
[4] => array(1) {
[0] => int(5)
}
[5] => array(1) {
[0] => int(8)
}
[6] => array(2) {
[0] => int(3)
[1] => int(8)
}
[7] => array(2) {
[0] => int(2)
[1] => int(5)
}
[8] => array(2) {
[0] => int(3)
[1] => int(8)
}
}
一定是这样的
array(7) {
[2] => array(1) {
[0] => int(0)
}
[3] => array(1) {
[0] => int(0)
}
[4] => array(1) {
[0] => int(0)
}
[5] => array(1) {
[0] => int(1)
}
[6] => array(1) {
[0] => int(0)
}
[7] => array(1) {
[0] => int(0)
}
[8] => array(1) {
[0] => int(1)
}
}
您可以使用数组映射()
和序列化()
:
如果以前没有使用过值,则分配false
;如果以前使用过值,则分配true
——但您要求的是整数,表示以前使用过的次数,对吗?
<?php
$new_array = array();
$indicator = array();
$current_array = array(
"2" => array(3),
"3" => array(8),
"4" => array(5),
"5" => array(8),
"6" => array(3,8),
"7" => array(2,5),
"8" => array(3,8),
);
foreach($current_array as $key => $value){
if(!in_array($value, $new_array, true)){
$new_array[$key] = $value;
$indicator[$key] = false;
} else {
$indicator[$key] = true;
}
}
var_dump($indicator);
<?php
$data = [
2 => [
3,
],
3 => [
8,
],
4 => [
5,
],
5 => [
8,
],
6 => [
3,
8,
],
7 => [
2,
5,
],
8 => [
3,
8,
],
];
$occurrences = [];
$mapped = array_map(function (array $values) use (&$occurrences) {
// create serialized representation of the values
// which we can use as an index
$index = serialize($values);
// haven't seen these values before
if (!array_key_exists($index, $occurrences)) {
$occurrences[$index] = 1;
return 0;
}
// increase our counter
$occurrences[$index]++;
return $occurrences[$index] - 1;
}, $data);
var_dump($mapped);