Skip to content
Advertisement

How to append arbitrary values to duplicate values in array php

I have photo array like

$array=[['key1' => 'a', 'key2'=>'duplicate']['key1' =>'b', 'key2'=>'duplicate']]

I need it like

$array=[['key1' => 'a', 'key2'=>'duplicate-x57gg']['key1' =>'b', 'key2'=>'duplicate-hdd67']]

How to do it in php

Advertisement

Answer

is it what you look for ?

this is working code, you can copy to test the output and try modify the $array to test different output.

//random number generator
function generateRandomString($length = 10, $excluded=[]) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    if(in_array($randomString,$excluded)){
      $randomString = generateRandomString($length,$excluded);
    }
    return $randomString;
}

$array=[['key1' => 'a', 'key2'=>'duplicate'],['key1' =>'b', 'key2'=>'duplicate'],['key1' =>'c', 'key2'=>'non-duplicate'],['key1' =>'d', 'key2'=>'duplicate']];
$array_loop = $array;//for looping use

$RANDOM_STRING_USED =[];

foreach($array_loop as $index => $a){
  //get duplicated array
  $arr_duplicated = array_filter($array,function($v) use ($a){
    //exlude self
    if($v['key1'] != $a['key1'] && $v['key2'] == $a['key2']){
      return true;
    }
  });

  //set randome string to duplicated array
  $is_duplicated = false;
  foreach($arr_duplicated as $dup){
    //get index of array
    $key = array_search($dup['key1'], array_column($array, 'key1'));
    
    $rand_str = generateRandomString(4,$RANDOM_STRING_USED);//in case random string occur
    $RANDOM_STRING_USED[] = $rand_str;
    $array[$key]['key2'] .= '-'.$rand_str;
    
    $is_duplicated = true; //set to true, for update current array as well
  }
  
  //if duplicated, update current array as well
  if($is_duplicated){
    $rand_str = generateRandomString(4,$RANDOM_STRING_USED);//in case random string occur
    $RANDOM_STRING_USED[] = $rand_str;
    $array[$index]['key2'] .= '-'.generateRandomString(4,$RANDOM_STRING_USED);
  }
}
echo '<pre>';
print_r($array);
echo '</pre>';
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement