重命名PHP Laravel中的对象键名称 [英] Renaming object keys name in PHP Laravel
本文介绍了重命名PHP Laravel中的对象键名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON请求,我需要更改所有与模型对象键相似的对象键名,我在嵌套数组对象方面遇到困难,并且点符号在这部分上不起作用.
I have a JSON request and i need to change all object key names similar on my model object keys, i'm having a difficulty about nested array objects, and also dot notation is not working on this part.
这是我的验证请求中的代码:
Here is my code on my validation request:
<?php
namespace App\Http\Requests\Api\Nutmeg;
use Illuminate\Foundation\Http\FormRequest;
class WebhookValidation extends FormRequest
{
protected $map = [
'callback_url' => 'url',
'tokenApi' => 'secret_token',
'supplier' => 'agent',
'supplier.*.key.*' => 'id',
'supplier.*.number.*' => 'quantity'
];
protected $jsonConvert;
public function setJson($json)
{
foreach($this->map as $original => $new) {
$json->set($new, $json->get($original));
$json->remove($original);
}
$this->jsonConvert = $json;
}
public function validationData()
{
return $this->jsonConvert->all();
}
public function rules()
{
return [
'url' => 'bail|required|url|unique:webhooks,url',
'secret_token' => 'required',
'agent.*.id' => 'required',
'agent.*.quantity' => 'required'
];
}
public function messages()
{
return [
'url.unique' => 'Url should be unique',
'secret_token.required' => 'Secret token is required'
];
}
}
这是JSON请求:
{
"callback_url": "https://www.gosdoddgle.com",
"tokenApi": "stringstrinngstringstring",
"supplier": [
{
"key": "sdsds1",
"number": "sdsds1"
},
{
"key": "sdsds1",
"number": "sdsds1"
}
]
}
从那开始,我希望它像这样:
From that i want it to be like this:
{
"url": "https://www.gosdoddgle.com",
"secret_token": "stringstrinngstringstring",
"agent": [
{
"id": "sdsds1",
"quantity": "sdsds1"
},
{
"id": "sdsds1",
"quantity": "sdsds1"
}
]
}
推荐答案
使用新键解码为array和array_combine.
然后循环代理",并再次用array_combine替换密钥.
Decode to array and array_combine with the new keys.
Then loop the 'agent' and replace the keys again with array_combine.
$arr = json_decode($json, true);
$mainkeys = ["url", "secret_token", "agent"];
$subkeys = ["id", "quantity"];
$arr = array_combine(array_slice($mainkeys,0,count($arr)), $arr);
if(isset($arr["agent"])){
foreach($arr["agent"] as &$val){
$val = array_combine($subkeys, $val);
}
}
unset($val);
array(3) {
["url"]=>
string(26) "https://www.gosdoddgle.com"
["secret_token"]=>
string(25) "stringstrinngstringstring"
["agent"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(6) "sdsds1"
["quantity"]=>
string(6) "sdsds1"
}
[1]=>
&array(2) {
["id"]=>
string(6) "sdsds1"
["quantity"]=>
string(6) "sdsds1"
}
}
}
这篇关于重命名PHP Laravel中的对象键名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文