Reputation: 1
I have an array with values
[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]
and i have another array
[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]
I need an array of values with two arrays match with its id .
expected output
[{
"": "",
"Gender":"male"
"Age": "27"
}, {
"": "",
"Gender": "female",
"Age": "26",
"Address Line": "japan"
}]
can anyone help to get the expected output.
Upvotes: 0
Views: 63
Reputation: 607
You can try this!
<?php
$jsonString1 = '[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]';
$jsonString2 = '[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]';
$array1 = json_decode($jsonString1, true);
$indexes = array();
foreach ($array1 as $element) {
$indexes[$element['id']] = $element['pf_label'];
}
$array2 = json_decode($jsonString2, true);
foreach ($array2 as $element) {
foreach ($element as $key => $value) {
if ($key) {
$singleElement[$indexes[$key]] = $value;
} else {
$singleElement[""] = "";
}
}
$result[] = $singleElement;
}
var_dump($result);
Upvotes: 0
Reputation: 347
Please try below solution
$json = '[{
"id": "17",
"pf_label": "Gender"
},
{
"id": "18",
"pf_label": "Age"
},
{
"id": "12",
"pf_label": "Address Line"
}
]';
$jsondec = json_decode($json,true);
foreach ($jsondec as $key => $value) {
$newjson[$value['id']] = $value['pf_label'];
}
$json2 = '[{
"": "",
"17": "male",
"18": "27"
}, {
"": "",
"17": "female",
"18": "26",
"12": "japan"
}]';
$jsondec2 = json_decode($json2,true);
foreach ($jsondec2 as $key => $value) {
foreach ($value as $key => $value) {
$newary[$newjson[$key]] = $value;
}
$finalary[] = $newary;
}
$result = json_encode($finalary);
Hope this will help you!
Upvotes: 1