php - 如何在样本数组中查找重复值
问题描述
如何使用php在示例数组中查找重复值
Array
(
[id] => 644
[qty] => 1
[product] => 127
[super_attribute] => Array
(
[140] => 16
)
)
Array
(
[id] => 648
[qty] => 1
[product] => 111
[super_attribute] => Array
(
[140] => 18
)
)
Array
(
[id] => 652
[qty] => 1
[product] => 111
[super_attribute] => Array
(
[140] => 18
)
)
在上面的数组中,我想找到重复的 [product] => 111 和 [140] => 18 。我怎样才能做到这一点?
解决方案
一种可能的方法是将您要查找的两个元素组合成一个较长的键,然后创建一个二维数组,列出所有具有新键的 ID。
在下面的代码中,我将product
数字乘以 1000,添加 的值super_attribute[140]
并将结果转换为字符串。根据您对正在使用的数据的了解,还有其他方法可以获得新密钥。
<?php
$arr = [
[
"id" => 644,
"qty" => 1,
"product" => 127,
"super_attribute" => [
"140" => 16
]
],
[
"id" => 648,
"qty" => 1,
"product" => 111,
"super_attribute" => [
"140" => 18
]
],
[
"id" => 652,
"qty" => 1,
"product" => 111,
"super_attribute" => [
"140" => 18
]
]
];
$dup = [];
foreach($arr as $subArr) {
// Calculate the new combined key
$newKey = (string)($subArr['product']*10000+$subArr["super_attribute"][140]);
// If we don't have this new key, create an array with the ID,
// otherwise, add the ID to the existing array for the new key.
if (isset($dup[$newKey])) {
$dup[$newKey][] = $subArr['id'];
} else {
$dup[$newKey] = [$subArr['id']];
}
}
var_dump($dup);
输出:
array (size=2)
1270016 =>
array (size=1)
0 => int 644
1110018 =>
array (size=2) //IDs with the combined key 111 and 18
0 => int 648
1 => int 652
推荐阅读
- html - 使用具有最大宽度的 React 创建一个图像库,一旦屏幕宽度小于最大宽度,它就会变小
- spring - Spring Boot JSON 配置返回 null
- javascript - 如何将 code.gs 中的变量添加到 Audio src?
- c# - ASP.NET CORE 5.0 Identity 显示当前登录用户
- python - 在 pandas 中使用 for 循环创建新列
- php - MySQL检查大量数据
- python-3.x - LazyDocs - 生成的 *.md 文件不代表项目符号列表
- php - 调用未定义的方法 Illuminate\Database\Query\Builder::with() - Larvel
- selenium - 我们如何在 jmeter 中对 selenoid 运行 Selenium 测试?
- python - 为什么 Python 不喜欢与成员变量进行比较?