Modify a JSON Array ID with PHP

I'm trying to update the name of a JSON array in PHP.

My array looks like:

arrayName: {
           key:var,
           key:var,
          etc
}

I would like to modify arrayName with another label.

1 answer

  • answered 2019-06-12 00:21 man0v

    The json you have provided is not a valid one... Assuming this is your json:

    $json = '{"array_name": {
               "key1":"var",
               "key2":"var",
                    "etc": ""
    }}';
    

    You can do something like:

    $your_label = 'some_label';
    $json = '{"array_name": {
               "key":"var",
               "key":"var",
                    "etc": ""
    }}';
    
    $tmp = json_decode($json, true);
    
    foreach($tmp as $k=>$v) {
    
            $out[$your_label] = $v; 
    
    }
    
    $your_dream_json = json_encode($out);