如何使用PHP或jQuery在JSON文件中设置正确的$key=>$value关联


How to set correct $key=>$value association in a JSON file using PHP or jQuery

我需要重新格式化我的JSON文件,以便数组中的值现在是该数组的键。

{
    "ID": "M-420",
    "ProductName": "example product name ",
    "ProductDescription": "example description",
    "Color": "blue "
},
{
    "ID": "M-421",
    "ProductName": "example product name ",
    "ProductDescription": "example description",
    "Color": "yellow "
}

{
    "M-420": {
        "ProductName": "example product name ",
        "ProductDescription": "example description",
        "Color": "blue "
    }
},
{
    "M-421": {
        "ProductName": "example product name ",
        "ProductDescription": "example description",
        "Color": "blue "
    }
}

我需要能够使用PHP抓取每个唯一ID的属性。我正在使用$json_decode();

将JSON转换为关联数组

感谢!

$new_array = array();
foreach ($array as $element) {
    $new_array[$element['ID']] = $element;
}

很简单的解决方案是:

$json_obj_old = json_decode($json_before_process);
$json_obj_new = array();
foreach($json_obj_old as $json_element){
  $json_obj_new[$json_element['ID']] = $json_element;
  unset($json_obj_new[$json_element['ID']]['ID']);
}
return json_encode($json_obj_new);