[英]How can i add a unique identifier to the same value of specific key in php array
I have an array 我有一个数组
Array
(
[0] => Array
(
[proomsize] => dasfdsfdsf
[proomtype] => Bedroom
)
[1] => Array
(
[proomsize] => dasfdsfsd
[proomtype] => Bedroom
)
[2] => Array
(
[proomsize] => dfadsf
[proomtype] => KitchenDinner
)
[4] => Array
(
[proomsize] => dafdsads
[proomtype] => Reception
)
[5] => Array
(
[proomsize] => fdsafdsfdsf
[proomtype] => Reception
)
[6] => Array
(
[proomsize] => adfadfdsf
[proomtype] => Reception
)
)
Now i need is if there is more than one $array['proomtype'] of same value i want to append a number at the end in my foreach loop.. so when i loop through it i want a result like this 现在我需要的是,如果有多个相同值的$ array ['proomtype'],我想在我的foreach循环的末尾附加一个数字..因此,当我循环通过它时,我想要这样的结果
Bedroom 1 : dasfdsfdsf
Bedroom 2 : dasfdsfsd
KitchenDinner : dfadsf
Reception 1 : dasfdsfsd
Reception 2 : adfdsf
Reception 3 : dfdfdf
how can i achieve that in a single loop i have tried using this 我如何在单个循环中尝试使用此功能
<?php
$BedroomCounter = 0;
if ($value['proomtype'] == 'Bedroom') {
if ($BedroomCounter == 0) {
echo $value['proomtype'] ':' .$value['proomsize'] . '<br>';
}else{
echo $value['proomtype'] . $BedroomCounter . ':' .$value['proomsize'] . '<br>';
}
$BedroomCounter++;
}
the issue is i have repeat this for each n every roomtype.. which is not something i want to. 问题是我对每个房间类型的每n个重复一次..这不是我想要的。
The way this works is by first using array_count_values()
to count the number of each type of room, this helps know when we need to add a suffix or not. 它的工作方式是首先使用
array_count_values()
来计算每种类型的房间的数量,这有助于知道何时需要添加后缀。
It then creates a copy of this array with the current counter for each room type starting at 1 using array_fill_keys()
. 然后,它使用
array_fill_keys()
从1开始为每种房间类型创建一个具有当前计数器的数组副本。
The code then loops through all of the entries looking up the room type and if the room type has more than 1 entry it adds the suffix from the counter array and increments that counter. 然后,该代码循环遍历查找房间类型的所有条目,如果房间类型具有多个条目,它将添加计数器数组的后缀并递增该计数器。
$duplicates = array_count_values(array_column($value, "proomtype"));
$currentCount = array_fill_keys(array_keys($duplicates), 1);
foreach ( $value as $key=>$entry ){
if ( $duplicates[$entry["proomtype"]] > 1 ) {
$value[$key]["proomtype"] .= " ".$currentCount[$entry["proomtype"]];
$currentCount[$entry["proomtype"]]++;
}
}
print_r($value);
The output with your example data is... 带有示例数据的输出为...
Array
(
[0] => Array
(
[proomsize] => dasfdsfdsf
[proomtype] => Bedroom 1
)
[1] => Array
(
[proomsize] => dasfdsfsd
[proomtype] => Bedroom 2
)
[2] => Array
(
[proomsize] => dfadsf
[proomtype] => KitchenDinner
)
[4] => Array
(
[proomsize] => dafdsads
[proomtype] => Reception 1
)
[5] => Array
(
[proomsize] => fdsafdsfdsf
[proomtype] => Reception 2
)
[6] => Array
(
[proomsize] => adfadfdsf
[proomtype] => Reception 3
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.