php: rename duplicate keys by giving number in for

2019-08-09 04:34发布

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

3条回答
Evening l夕情丶
2楼-- · 2019-08-09 05:12
if($data[0]=$data[0]+1){$n="1";}else{$n="";}

Use == instead of = for the if statements

查看更多
We Are One
3楼-- · 2019-08-09 05:18

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];
}
查看更多
甜甜的少女心
4楼-- · 2019-08-09 05:19

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++;
 }
查看更多
登录 后发表回答