php - Add numbering to duplicate array items
I'm writing a script to increment values that are repeated in an array. For example, an array containing these 5 values:
Test
Testing
Test
Testing Again
Test
Should become:
Test
Testing
Test 1
Testing Again
Test 2
Here's what I have so far:
$custom_fields = get_post_meta( $post_id, 'fields', false);
$custom_field_occurences = [];
foreach ($custom_fields as $key => $value) {
if (!in_array($value, array_keys($custom_field_occurences))) {
// First instance, doesn't need to be incremented,
$custom_field_occurences[$value] = 0;
} else {
// Already exists, increment it by the number of occurences.
$custom_field_occurences[$value]++;
$incremented_value = $value . ' ' . $custom_field_occurences[$value];
update_post_meta( $post_id, 'fields', $incremented_value, $value );
}
}
The problem I'm currently having is that the function turns the array into this:
Test 1
Testing
Test 1
Testing Again
Test 1
I have also tried this variation:
foreach ($cleaned_custom_fields as $key => $value) {
if (!in_array($value, array_keys($custom_field_occurences))) {
// First instance, doesn't need to be incremented,
$custom_field_occurences[$value] = 0;
} else {
// Already exists, increment it by the number of occurences.
$custom_field_occurences[$value]++;
}
$incremented_value = $value . ' ' . $custom_field_occurences[$value];
update_post_meta( $post_id, 'wpcf-logbook-text-fields', $incremented_value, $value );
}
But that results in
Test 0
Testing 0
Test 0
Testing Again 0
Test 0
How can I ensure the function incrementally numbers the repeating values, making them unique?
Answer
Solution:
I am sure this will work
<?php
$arrayName = array('Test','Testing','Test','Testing again','Test','Testing');
for($i=0;$i<count($arrayName);$i++){
$c=1;
for($j=$i+1;$j<count($arrayName);$j++){
if($arrayName[$i]==$arrayName[$j]){
$arrayName[$j].=$c;
$c++;
}
}
}
for($i=0;$i<count($arrayName);$i++){
echo $arrayName[$i].'<br>';
}
?>
Answer
Solution:
Solution ended up being this:
$cleaned_custom_fields = get_post_meta( $post_id, 'fields', false);
$incremented_fields = [];
$field_occurences = [];
foreach ($cleaned_custom_fields as $key => $value) {
if (!in_array($value, array_keys($incremented_fields))) {
// First instance, doesn't need to be incremented. Just push it
array_push($incremented_fields, $value);
$field_occurences[$value] = 0;
} else {
// Already exists, increment it by the number of occurences.
$field_occurences[$value]++;
$incremented_value = $value . ' ' . $field_occurences[$value];
array_push($incremented_fields, $incremented_value);
update_post_meta( $post_id, 'fields', $incremented_value, $value );
}
}
Source