如何在 Laravel 控制器函数中将数组格式化为特定格式?

发布于 2025-01-18 15:28:52 字数 841 浏览 2 评论 0原文

我目前正在创建Laravel Vue水疗中心,只是想知道如何使用这些名称ID的名称使用相同的结构。这是名称ID的JSON:

[
  [
    1,
    5
  ],
  [
    1,
    3
  ]
]

这是我的getDesignations employscontroller.php

    public function getDesignations($id) {
        $employee_designation_ids = Employees::find($id)->pluck('designation_id')->toArray();
        $designation_name = [];
        foreach ($employee_designation_ids as $employee_designation_id) {
            $designation = Designations::where('id', '=', $employee_designation_id); 
            //$designation_name[] =  $designation;
        }

        return $employee_designation_ids;
    }

I'm currently creating a laravel vue spa, and just wondering on how can I get designation names with these designation id's with the same structure. This is the json of designation id's:

[
  [
    1,
    5
  ],
  [
    1,
    3
  ]
]

This is my getDesignations function in EmployeesController.php:

    public function getDesignations($id) {
        $employee_designation_ids = Employees::find($id)->pluck('designation_id')->toArray();
        $designation_name = [];
        foreach ($employee_designation_ids as $employee_designation_id) {
            $designation = Designations::where('id', '=', $employee_designation_id); 
            //$designation_name[] =  $designation;
        }

        return $employee_designation_ids;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑,眼淚并存 2025-01-25 15:28:52

如果您特别想要这种格式,您可以这样做(我有很多猜测,因为您没有共享您的表结构)

public function getDesignations($id) {
    $employee_designation_ids = Employees::find($id)->designation_id;
    return [[$id, $employee_designation_ids]];
}

但是为什么您要为单行结果返回双表。

If you want specifically that format, you can do it like this (with a lot of guesses in my part since you did not share your Tables structures)

public function getDesignations($id) {
    $employee_designation_ids = Employees::find($id)->designation_id;
    return [[$id, $employee_designation_ids]];
}

But why are you returning a double table for a single row result.

蓝海 2025-01-25 15:28:52

感谢您的帮助!我已经在控制器中使用了此方法来解决它:

public function getDesignations(Request $request, $id) {
        $employee_designation_ids = Employees::where('id', $id)->pluck('designation_id');
        return Designations::whereIn('id', $employee_designation_ids[0])->pluck('name');
    }

Thanks for all your help! I've managed to fix it with this method in my controller:

public function getDesignations(Request $request, $id) {
        $employee_designation_ids = Employees::where('id', $id)->pluck('designation_id');
        return Designations::whereIn('id', $employee_designation_ids[0])->pluck('name');
    }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文