php合并两个数组以获得预期的o/p

hvvq6cgz  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(418)

我有一个值数组

[{
        "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"
}]

有人能帮忙得到预期的结果吗。

pb3skfrl

pb3skfrl1#

请尝试下面的解决方案

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

希望这对你有帮助!

v9tzhpje

v9tzhpje2#

你可以试试这个!

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

演示

相关问题