如何在示例数组中查找重复值
How to find duplicate value in sample array
如何使用 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
如何使用 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