php: rename duplicate keys by giving number in foreach

丶灬走出姿态 提交于 2019-12-13 00:28:47

问题


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



来源:https://stackoverflow.com/questions/23540944/php-rename-duplicate-keys-by-giving-number-in-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!