我想在multidimentional数组中只获取重复记录。 我的数组看起来像:
"items": [
{
"id": "1",
"father_name": "YYY",
"surname": "XXX",
"name": "abc",
},
]
我想获得像
这样的结果{{1}}
我怎样才能得到它?请帮帮我,我被困在这里。
我尝试了很多东西,但一切都在单维数组中运行
提前致谢!
答案 0 :(得分:2)
作为其他答案的替代方案,您还可以执行以下操作:
$duplicates = [];
while ($a = array_shift($array)) {
if (in_array($a, $array) && !in_array($a, $duplicates)) {
$duplicates[] = $a;
}
}
希望这有帮助!
答案 1 :(得分:1)
给定数据是json字符串。
假设您的数组结构相同,请尝试:
$arr = array("items"=>array(
"id"=> "1",
"father_name"=> "YYY",
"surname"=> "XXX",
"name"=> "abc",
),
array(
"id"=> "1",
"father_name"=> "YYY",
"surname"=> "XXX",
"name"=> "abc",
),
array(
"id"=> "2",
"father_name"=> "ZZZ",
"surname"=> "UUU",
"name"=> "abc",
)
);
$withoutDuplicates = array_unique($arr, SORT_REGULAR);
$duplicates = array_diff_assoc($arr, $withoutDuplicates);
echo "<pre>";
print_r($duplicates);
输出:
阵 ( [0] =&gt;排列 ( [id] =&gt; 1 [father_name] =&gt; YYY [姓] =&gt; XXX [name] =&gt; ABC ))
答案 2 :(得分:0)
<?php
$arr = array(
'items' => array(
0 => array(
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
),
1 => array(
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
),
2 => array(
'id' => '2',
'father_name' => 'ZZZ',
'surname' => 'UUU',
'name' => 'abc'
)
)
);
$result = array();
for ($i = 0; $i < count($arr['items'])-1; $i++) {
for ($x = $i+1; $x < count($arr['items']); $x++) {
if ($arr['items'][$i] !== $arr['items'][$x] || in_array($arr['items'][$i], $result))
continue;
array_push($result, $arr['items'][$i]);
}
}
print_r($result);
?>
一种方法,假设你正在使用多维php数组。
答案 3 :(得分:0)
您可以这样做:
foreach($items as $key => $item)
{
unset($items[$key]);
if(array_search($item['id'], array_column($items, 'id_or_another_key')))
{
$result[] = $item;
}
}
接下来是这个代码的意义:
答案 4 :(得分:0)
<?php
/**
* @param $data array
*
* @return array
*/
function getDuplicatesOnly(array $data): array
{
$result = [
'items' => [
],
];
foreach ($data as $key => $datum) {
$itemId = $datum['id'];
unset($data[$key]);
$columns = array_column($data, 'id');
if(in_array($itemId, $columns)) {
$result['items'][] = $datum;
}
}
return $result;
}
$testData = [
'input' => [
'items' => [
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
],
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
],
[
'id' => '2',
'father_name' => 'ZZZ',
'surname' => 'UUU',
'name' => 'abc'
]
]
],
'output' => [
'items' => [
[
'id' => '1',
'father_name' => 'YYY',
'surname' => 'XXX',
'name' => 'abc'
]
],
],
];
$output = getDuplicatesOnly($testData['input']['items']);
assert($testData['output'] == $output, "Failed asserting data.");
可以测试here。