在Laravel中,我执行了一个JSON映射,其中我需要将JSON转换为不同的模式.为此,我遵循以下步骤:
- 用Arr::dot helper点array.这样我就得到了这个结果,例如:
array(11) {
["0.identificador"]=>
int(1)
["0.nome_completo"]=>
string(8) "John Doe"
["0.email"]=>
string(11) "j@email.com"
["0.empresa.razao_social"]=>
string(11) "ABC Company"
["0.empresa.endereco"]=>
string(11) "123 Main St"
["0.pedidos.0.SKU"]=>
int(1)
["0.pedidos.0.descricao"]=>
string(5) "Shoes"
["0.pedidos.0.qtd"]=>
int(2)
["0.pedidos.1.SKU"]=>
int(2)
["0.pedidos.1.descricao"]=>
string(5) "Shirt"
["0.pedidos.1.qtd"]=>
int(1)
}
- 迭代通过点数组,并与我的键映射进行比较.如果它们匹配,我用映射键设置值.
我的映射看起来像这样:
array(8) {
["*.identificador"]=> string(4) "*.id"
["*.nome_completo"]=> string(6) "*.name"
["*.empresa"]=> string(9) "*.company"
["*.empresa.razao_social"]=> string(14) "*.company.name"
["*.empresa.endereco"]=> string(17) "*.company.address"
["*.pedidos.*.SKU"]=> string(13) "*.orders.*.id"
["*.pedidos.*.descricao"]=> string(18) "*.orders.*.product"
["*.pedidos.*.qtd"]=> string(19) "*.orders.*.quantity"
}
这就是我的代码到目前为止的样子:
$payload = [
[
"identificador" => 1,
"nome_completo" => "John Doe",
"email" => "j@email.com",
"empresa" => [
"razao_social" => "ABC Company",
"endereco" => "123 Main St"
],
"pedidos" => [
[
"SKU" => 1,
"descricao" => "Shoes",
"qtd" => 2
],
[
"SKU" => 2,
"descricao" => "Shirt",
"qtd" => 1
]
]
]
];
$dottedPayload = Arr::dot($payload);
$transformedPayload = [];
foreach ($dottedPayload as $key => $value) {
$newKey = preg_replace('/\d+./', '*.', $key);
$newKey = preg_replace('/\.\d+\./', '.*.', $newKey);
$newKey = preg_replace('/\.\d+$/', '.*', $newKey);
$mappedKey = $mappingConfig[$newKey] ?? $key;
data_fill($transformedPayload, $mappedKey, $value);
}
我的输出是这样的:
array(2) {
["*"]=>
array(4) {
["id"]=>
int(1)
["name"]=>
string(8) "John Doe"
["company"]=>
array(2) {
["name"]=>
string(11) "ABC Company"
["address"]=>
string(11) "123 Main St"
}
["orders"]=>
array(1) {
["*"]=>
array(3) {
["id"]=>
int(2)
["product"]=>
string(5) "Shirt"
["quantity"]=>
int(1)
}
}
}
[0]=>
array(1) {
["email"]=>
string(11) "j@email.com"
}
}
但这是预期的:
$expectedResult = [
[
"id" => 1,
"name" => "John Doe",
"email" => "j@email.com",
"company" => [
"name" => "ABC Company",
"address" => "123 Main St"
],
"orders" => [
[
"id" => 1,
"product" => "Shoes",
"quantity" => 2
],
[
"id" => 2,
"product" => "Shirt",
"quantity" => 1
]
]
]
];
如何在映射后正确取消数组的点,使用通配符,正确设置索引?任何其他建议来执行这个JSON映射也是受欢迎的.