我有一个包含产品的数组,我想搜索重复的名称并增加重复的值
我试图创建一个空数组并将所有标题值键[0]推送到它,然后我发现我对每个具有array_count_values的键[0]的值有多少重复。
这是我的阵列;
$products=Array
(
[0] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[1] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[2] => Array
(
[0] => 'Intel I3',
[1] => 250,
[2] => 'intel-i3'
),
[3] => Array
(
[0] => 'AMD graphic',
[1] => 146,
[2] => 'amd-graphic'
)
);
我希望这个结果增加1。
我怎样才能得到这个结果?
$products=Array
(
[0] => Array
(
[0] => 'Intel I3',
[1] => 146,
[2] => 'intel-i3'
),
[1] => Array
(
[0] => 'Intel I3_1',
[1] => 146,
[2] => 'intel-i3'
),
[2] => Array
(
[0] => 'Intel I3_2',
[1] => 250,
[2] => 'intel-i3'
),
[3] => Array
(
[0] => 'AMD graphic',
[1] => 146,
[2] => 'amd-graphic'
)
);
答案 0 :(得分:3)
$titleCounts = array();
foreach ($products as &$product) {
if (!isset($titleCounts[$product[0]])) {
$titleCounts[$product[0]] = 0;
} else {
$titleCounts[$product[0]]++;
$product[0] = ($product[0].'_'.$titleCounts[$product[0]]);
}
}
你可以在这里看到这个工作:
答案 1 :(得分:0)
<?php
$counter = [];
$i = 0;
foreach($products as $product){
$counter[] = $product[2];
$vals = array_count_values($counter);
$current_number = $vals[$product[2]];
if($current_number)
$products[$i][0] .= '_'.$current_number;
$i++;
}
应该这样做。
答案 2 :(得分:0)
经过测试,确实有效。
$tmpArray = array();
foreach ($products as &$product) {
$name = $product[0];
if (array_key_exists($name, $tmpArray)) {
$product[0] = $name . '_' . $tmpArray[$name];
$tmpArray[$name]++;
} else {
$tmpArray[$name] = 1;
}
}
unset($product);