首页 > 解决方案 > 如何在 laravel 中访问数组值

问题描述

我用于使用 ajax 调用及其工作将 currentTime 存储在数据库中的这种方法

public function saveTime(Request $request, $lession_id){

$user = Auth::user();
if($user === null){
    return response()->json(['message' => 'User not authenticated', 404]);
}

$video = \App\Lession::where('id',$lession_id)->first();

$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere


$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
  array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
  $founder = false;
  $watch_history_array = json_decode($watch_history, true);
  for ($i = 0; $i < count($watch_history_array); $i++) {
    $watch_history_for_each_lesson = $watch_history_array[$i];
    if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
      $watch_history_for_each_lesson['progress'] = $progress;
      $watch_history_array[$i]['progress'] = $progress;
      $founder = true;
    }
  }
  if (!$founder) {
  array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
  }
}

$data['watch_history'] = json_encode($watch_history_array);

$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);

  return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call

 }

但是,当我使用另一种方法来获取播放时间时,它会将数组放入数组中

public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
    return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;

foreach ($array as $key => $value) {
  echo $check;
}  
 }

我当前在数据库中的输出如下 [{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]

因此,请帮助我从中获取每个课程 ID 的值

标签: phplaravel

解决方案


推荐阅读