Foreach循环只返回最后一个值

Foreach loop returns only last value

本文关键字:最后一个 返回 循环 Foreach      更新时间:2023-09-26

我使用Laravel,从视图中获得一个数组,其中我想要的输入用句点分隔我有这个代码:

$addedskills = Input::get('addskills'); //array of values sep by period
   $addedskillsarray=explode(".",$addedskills); //gettin each value
    //array_slice() to remove the first element of the array bcz it's empty
   foreach(array_slice($addedskillsarray, 1) as $addnewskills)
      $skills = new Skill();
      $skills->skill_name = $addnewskills;
      $user->skills()->save($skills);
   }

//Javascript

$(document).ready(function(){ 
   $("#addlanguages").val(""); 
   $("#addskills").val(""); 
   $("#btnaddskills").click(function(){ 
      var skilltxt=$("#slctskill").val();
      $("#addbtnskill").append('<button name="newskill" type="button" class="btn lng-btn">'+skilltxt+'<span class="badge badge-danger custom-badge"><i class="fa fa-close"></i></span></button>'); 
      $("#addskills").val(inputvalueskills+'.'+skilltxt);
      var inputvalueskills=$("#addskills").val(); 
   });
});

问题是它只返回数组的最后一个值

为什么不在这里尝试array_filter

$addedskills = Input::get('addskills');
   $addedskillsarray= array_filter(explode(".",$addedskills));
   foreach($addedskillsarray as $addnewskills)
      $skills = new Skill();
      $skills->skill_name = $addnewskills;
      $user->skills()->save($skills);
   }