在数组内生成动态数组

我正在使用Laravel .if I dd() $arrBody I get following .if dd($arrBody);

    array:7[▼
            "first_name" => "john"
            "last_name" => "doe"
            "email_address" => "john@gmail.com",
            "age"=> 25,
            "date"=>"2021-07-9",
            "country"=>"USA",
            "code"=>"3045"
]

现在我想从$arryBody获取电子邮件、名字和姓氏,并将它们分配给电子邮件、first_name和last_name key。但是其他的键,比如年龄,国家,州和日期,我想让它们放在custom_fields数组中,但它就像是硬编码的。因为我是一个接一个地显示年龄、日期、国家。我的数组可能有更多的键/值,所以我想让custom_fields数组成为动态的。我希望custom_fields内部的field_name在$arrBody数组的email、first_name和last_name之后具有相同的名称,而不是手动编写field_name,并希望将该键值分配给" value“

$data = [
        "subscribers"=>[
            [
                "email"=> $arrBody['email'],
                "first_name"=> $arrBody['first_name'],
                "last_name"=> $arrBody['last_name'],
                "subscribed"=> true,
                
                "custom_fields"=>[
                    [ 
                        "field_name"=> "age",
                        "value_type"=> "text",
                        "value"=> array_key_exists('age',$arrBody) ? $arrBody['age']:''
                    ],
                    [ 
                        "field_name"=> "country",
                        "value_type"=> "text",
                        "value"=> array_key_exists('country',$arrBody) ? $arrBody['country']:''
                    ],
                    [ 
                        "field_name"=> "date",
                        "value_type"=> "text",
                        "value"=> array_key_exists('date',$arrBody) ? $arrBody['date']:''
                    ],
                    //so on...
                ]
            ]
        ]
    ];

在Laravel中我可以使用

$main = ['email', 'first_name', 'last_name'];

$subscriber = Arr::only($arrBody, $main);

$custom = Arr::exclude($arrBody, $main);

现在我希望这个$custom数组在"custom_fields"=>[]中动态,直到$custom数组的长度,而不是检查它是否有年龄,国家等。如果可能的话,就像这样

custom_fields" => [
                        [
                            "field_name" => array_keys($custom)
                            "value_type" => "text",
                            "value" => array_values($custom)
                        ],
            //go until the end of $custom array
];

转载请注明出处:http://www.sjzxcyzs.com/article/20230401/1061815.html