日安! 我正在使用php编写RestAPI.我的团队成员正在使用Reaction-Native使用API,他要求我将响应格式设置为以下格式

{
        title: 'Class of 2007',
        data: [
            { id: 1, lastsName: 'Igbashio', firstName: 'Kalifort', middleName: 'Kashimana', email: 'igbashiokalifortkashimana@gmail.com', image: 'https://img.freepik.com/premium-photo/young-student-caucasian-woman-isolated-white-background-pointing-side-present-product_1368-289762.jpg?w=740' },
            { id: 2, lastsName: 'Usman', firstName: 'Bello', middleName: '', email: 'usmanbello@gmail.com', image: 'https://img.freepik.com/free-photo/waist-up-portrait-handsome-serious-unshaven-male-keeps-hands-together-dressed-dark-blue-shirt-has-talk-with-interlocutor-stands-against-white-wall-self-confident-man-freelancer_273609-16320.jpg?size=626&ext=jpg&ga=GA1.2.1337949710.1669025188' },
            { id: 3, lastsName: 'Manasseh', firstName: 'Isa', middleName: '', email: 'manassehisa@gmail.com', image: 'https://img.freepik.com/free-photo/young-attractive-handsome-guy-feels-delighted-gladden-amazed_295783-535.jpg?size=626&ext=jpg&ga=GA1.2.1337949710.1669025188' }
        ]
    },
    {
        title: 'Class of 2008',
        data: [
            { id: 4, lastsName: 'Igbashio', firstName: 'Sansa', middleName: 'Sewuese', email: 'igbashiosansaswewuese@gmail.com', image: 'https://img.freepik.com/free-photo/front-view-female-student-white-shirt-black-jacket-wearing-backpack-holding-files-with-copybooks-blue-wall-college-university-lessons_140725-43393.jpg?size=626&ext=jpg&ga=GA1.2.1337949710.1669025188' },
            { id: 5, lastsName: 'Yusuf', firstName: "Sa'atu", middleName: '', email: 'yusufsaatu@gmail.com', image: 'https://img.freepik.com/free-photo/cheerful-muslim-woman_53876-14375.jpg?w=360&t=st=1669732335~exp=1669732935~hmac=9942e2842661b423d7686f2ba66d87b2b9485e95f438b415993b38e910203937' },
            { id: 6, lastsName: 'Rimamtse', firstName: 'Bleesing', middleName: 'Fxiafatirimam', email: 'rimamblessing@gmail.com', image: 'https://img.freepik.com/premium-photo/smiling-black-woman-striped-shirt-with-arms-crossed_33839-10129.jpg?size=626&ext=jpg&ga=GA1.2.1337949710.1669025188' }
        ]
    },

以便在react 本机sectionList中使用. 以下是我到目前为止是如何完成这项任务的

$list = Members::where(function ($sql) use ($input) {
            if (isset($input["search"])) :
                return $sql->where('regNo', 'LIKE', $input["search"])->orWhere('lastsName', 'LIKE', $input["search"])
                    ->orWhere('firstName', 'LIKE', $input["search"])->orWhere('email', 'LIKE', $input["search"])
                    ->orWhere('phone', 'LIKE', $input["search"])->orWhere('gender', 'LIKE', $input["search"]);
            endif;
        })->orderBy('graduateYear', 'DESC')->orderBy('lastsName', 'ASC')->skip($input["start"])->take($input["length"])->get();
die(json_encode(formatMembers($list)));


private function formatMembers($list)
    {
        $json = array();
        $i = 0;
        $lastYear = null;
        foreach ($list as $x) {
            if (count($json) == 0) :
                $json[$i]["title"] = $x->graduateYear;
                $json[$i]['data'][] = array(
                    "id" => $x->id, "lastsName" => $x->lastsName, "firstName" => $x->firstName,
                    "middleName" => $x->middleName, "email" => $x->email, "image" => null
                );
                $lastYear = $x->graduateYear;
            else:
                if ($lastYear == $x->graduateYear) :
                    $json[$i]['data'][] = array(
                        "id" => $x->id, "lastsName" => $x->lastsName, "firstName" => $x->firstName,
                        "middleName" => $x->middleName, "email" => $x->email, "image" => null
                    );
                    $lastYear = $x->graduateYear;
                else :
                    $i++;
                    $json[$i]["title"] = $x->graduateYear;
                    $json[$i]['data'][] = array(
                        "id" => $x->id, "lastsName" => $x->lastsName, "firstName" => $x->firstName,
                        "middleName" => $x->middleName, "email" => $x->email, "image" => null
                    );
                    $lastYear = $x->graduateYear;
                endif;
            endif;
        }
        return $json;
    }

贝娄是我实施的结果

[
        {
            "title": "2016",
            "data": [
                {
                    "id": 6,
                    "lastsName": "Igbashio ",
                    "firstName": "Sansa",
                    "middleName": "Seember",
                    "email": "sansaigbashio@Gmail.com",
                    "image": null
                },
                {
                    "id": 7,
                    "lastsName": "Usman",
                    "firstName": "Smith",
                    "middleName": "",
                    "email": "smithusman@Gmail.com",
                    "image": null
                }
            ]
        }]

我的问题是,有没有更好的方法来实现这一点? 在处理大量记录甚至更短的方法时考虑. 任何理想都会受到欢迎. 提前谢谢您!

推荐答案

使用临时的第一级关联关键字帮助进行分组.迭代完成后,用array_values()go 掉第一级键;

代码:(Demo)

$grouped = [];
foreach ($array as $obj) {
    sscanf($obj->graduateYear, 'Class of %d', $year);
    unset($obj->graduateYear);
    $grouped[$year]['title'] = $year;  // doesn't matter that this is overwritten over and over
    $grouped[$year]['data'][] = $obj;
}
var_export(array_values($grouped));

还请注意有关Foreach循环内的变异对象的警告here.

Php相关问答推荐

Symfony/Panther Web抓取不适用于登录后的内容(云功能)

Laravel集合块()方法

无法在Laravel/Vue停靠容器中启动MySQL

将SVG包含在另一个php生成的SVG中

Chillerlan/php-iOS名称字段的QR vCard错误

如何在laravel中使用script type= text/html/script

未收到Strava WebHook事件数据

无额外字段的Laravel同步

WooCommerce中特定付款方式的变更订单预留库存时间

PHP Match如何准确判断条件?

将可编辑的计费自定义字段添加到 WooCommerce 管理单个订单

PHP Laravel 迁移文件不创建关系

如何在 Laravel 迁移中使用日期时间和天数?

将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

使用现有的htaccess的PHP路由脚本

在WooCommerce购物车和 checkout 页面中更改总计文本

PHP文件如何从CSS执行

在WooCommerce我的账户单个订单页面中添加订单商品部分和按钮

htaccess 无限循环问题

php-http/discovery 插件 1.15.1 是否仍在使用自己的模块 destruct Contao 4.13 中的composer 安装?