【问题标题】:Laravel - Can i add new item to an array based on the `id` value existing that array?Laravel - 我可以根据现有数组的“id”值将新项目添加到数组中吗?
【发布时间】:2021-12-10 03:23:43
【问题描述】:
array (
   0 =>
    array (
    'courseId' => 14,
    'tutorName' => 'admin',
    ),
   1 =>
    array (
    'courseId' => 15,
    'tutorName' => 'merl',
    ),
 )

var_export($response) 是一个类似上面的数组。对于$response 数组中的每个courseId,当$response 数组中的courseId 也存在student_learning 表时,我想找到pointssum。之后,我想将这个点的总和($points)添加到$response 数组中,作为对应courseId 的新项。在这里,问题是,$points 的每个值都作为新项目添加到 $response 数组的每个数据集中,但我希望它被添加到其各自的 $response 数组中 courseId 仅。我该怎么做?

foreach ($response as $key ) {
           
     $points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$key['courseId'])->sum('points');
     $res = array_map(function($e) use($points,$percent) { 
          $e['points'] = $points;
          return $e; }, $response);
    dump($res);
  }

dump($res) 给出如下输出

array:2 [
  0 => array:8 [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 12
  ]
  1 => array:8 [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 12
  ]
]
array:2 [
  0 => array:8 [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 3
  ]
  1 => array:8 [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 3
  ]
]

foreach 之外的dump($res) 给出如下输出

array:2 [
  0 => array:8 [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 3
  ]
  1 => array:8 [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 3
  ]
]

预期/要求的输出

  [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 12
  ]
  [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 3
  ]

【问题讨论】:

  • 所以你需要为每个数组添加点对吗?
  • @ManojKiranAppathurai 是的。请查看我的预期输出。这就是我想要的
  • 你能分享这两个表结构吗
  • @ManojKiranAppathurai 我认为答案无论如何都不会连接到表结构

标签: php arrays laravel eloquent laravel-8


【解决方案1】:

您可以在使用 foreach 循环时添加新的数组键

$response  = array (
   0 =>
    array (
    'courseId' => 14,
    'tutorName' => 'admin',
    ),
   1 =>
    array (
    'courseId' => 15,
    'tutorName' => 'merl',
    ),
 );

    $newResponse = [];
  foreach($response as $eachResponse){
    $points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$eachResponse['courseId'])->sum('points');
    
    $eachResponse['points'] = $points;
    $newResponse[] = $eachResponse;
  }
dd($newResponse);

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2014-10-17
    • 2015-08-10
    • 2017-07-08
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多