0

我有一个包含值的数组

[{
        "id": "17",
        "pf_label": "Gender"
    },
    {
        "id": "18",
        "pf_label": "Age"
    },
    {
        "id": "12",
        "pf_label": "Address Line"
    }
]

我有另一个数组

[{
    "": "",
    "17": "male",
    "18": "27"
}, {
    "": "",
    "17": "female",
    "18": "26",
    "12": "japan"
}]

我需要一个值数组,其中两个数组与其 id 匹配。

预期产出

[{
    "": "",
    "Gender":"male"
    "Age": "27"
}, {
    "": "",
    "Gender": "female",
    "Age": "26",
    "Address Line": "japan"
}]

任何人都可以帮助获得预期的输出。

4

2 回答 2

1

请尝试以下解决方案

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

希望对你有帮助!

于 2018-07-09T13:12:00.713 回答
0

你可以试试这个!

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

演示

于 2018-07-09T19:19:21.890 回答