0

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.

2
  • 3
    Can you show us what you've tried and what went wrong? SO is a problem solving community, not a free code society Commented Jul 9, 2018 at 12:40
  • What's the point of "" => ""? Commented Jul 9, 2018 at 12:44

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.