简体   繁体   English

php 中的数组推送和合并

[英]Array push and merge in php

How to merge one array with multple elements but the same index into on array with all index in PHP.如何将一个具有多个元素但索引相同的数组合并到具有 PHP 中所有索引的数组中。 I have one array look like this and i want to merge into one array.我有一个数组看起来像这样,我想合并到一个数组中。

data": [
        [
            {
                "req_recid": "REQ_0000000001",
                "req_name": "user doer",
                "req_branch": "user",
                "req_position": "userdoer",
                "req_from": "ho",
                "req_tpye": "1",
                "req_date": "Sat, Dec 12, 2020 7:36 PM"
            }
        ],
        [
            {
                "req_recid": "REQ_0000000004",
                "req_name": "Test",
                "req_branch": "Test",
                "req_position": "Test",
                "req_from": "ho",
                "req_tpye": "4",
                "req_date": "Sun, Dec 13, 2020 12:47 PM"
            }
            

        ]
    ]

and my expected result i want like this我想要这样的预期结果

data": [
        [
            {
                "req_recid": "REQ_0000000001",
                "req_name": "user doer",
                "req_branch": "user",
                "req_position": "userdoer",
                "req_from": "ho",
                "req_tpye": "1",
                "req_date": "Sat, Dec 12, 2020 7:36 PM"
            },
            {
                "req_recid": "REQ_0000000004",
                "req_name": "Test",
                "req_branch": "Test",
                "req_position": "Test",
                "req_from": "ho",
                "req_tpye": "4",
                "req_date": "Sun, Dec 13, 2020 12:47 PM"
            }
            
        ]
    ]

Anyone can help in PHP please.任何人都可以在 PHP 中提供帮助。

Since you want to change a multi-dimensional array to single dimension.由于您要将多维数组更改为单维数组。 Laravel has a beautiful collection method as flatten() . Laravel有一个漂亮的收集方法flatten() This flattens your multi dimensional array to single array.这会将您的多维数组展平为单个数组。 In your case you can use:在您的情况下,您可以使用:

$result = collect($data)->flatten();

to get the desired result.得到想要的结果。

Know more about it: https://laravel.com/docs/8.x/collections#method-flatten了解更多: https://laravel.com/docs/8.x/collections#method-flatten

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM