Foreach循环仅返回最后一个值

时间:2016-05-11 08:26:50

标签: javascript laravel-5.2

我正在使用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(); 
   });
});

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

1 个答案:

答案 0 :(得分:0)

为什么不在这里尝试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);
   }