php: rename duplicate keys by giving number in for

2019-08-09 04:23发布

问题:

i have a form data and the data's array like this:

$datas=array("x-1","y-2","y-2","y-3","t-1");

my foreach loop:

    foreach($datas as $x => $data){
    $data=explode("-",$data);
    if($data[0]==$data[0]+1){$n=1;}else{$n=0;}
    $keys[$x]=$data[0].$n++;
    $vals[$x]=$data[1];
}

i couldn't write the true code, my 3rd line is wrong i think (if($data[0]=$data[0]+1){$n="1";}else{$n="";}) so, i wanna rename the duplicate keys by giving number. my output should be like this:

x=1 y1=1    y2=2    y3=2    t1=1

回答1:

Try

     $datas=array("x-1","y-2","y-2","y-3","t-1");

     $i=0;
     $n=1;
     foreach($datas as $x => $data){
     $data=explode("-",$data);
     $data2=explode("-",$datas[$i+1]);
     if($data[0]==$data2[0])
      {  
      $keys[$x]=$data[0].$n; 
      $n=$n+1;
      }
      else
     {
     $keys[$x]=$data[0].$n; 
     $n=0;
     }

       $vals[$x]=$data[1];
    $i++;
 }


回答2:

This code has error you use = Which will assign value , not compare it.
also n should be integer not string
To fix that

  foreach($datas as $x => $data){
    $data=explode("-",$data);
    if($keys[$x]==$keys[$x+1]){$n=1;}else{$n=0;}
    $keys[$x]=$data[0].$n++;
    $vals[$x]=$data[1];
}


回答3:

if($data[0]=$data[0]+1){$n="1";}else{$n="";}

Use == instead of = for the if statements