KOTIOS
KOTIOS

Reputation: 11194

Decoding json in array , editing array and encoding in json - PHP

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :

   $json = json_decode(file_get_contents('all_json_files/jobs.json'), true); 
    foreach ($json as $key=>$row){
      foreach ( $row as $key=>$row){
         foreach ( $row as $key=>$row){
            foreach ($row as $key=>$row){
               if(strcmp($key,"security_block")==0)
                {
                       foreach ($row as $k=>$r){
                       if(strcmp($k,"job_payload_hash")==0)
                       {
                         $row[$k]['job_payload_hash']=$base64String;
                         print_r($row);
                       }
                }
              }
            }
         }
       }
    }
    print_r($json);

Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .

Upvotes: 0

Views: 106

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173642

If the key could appear anywhere, the answer is pretty simple:

function update_hash(&$item, $key, $base64String)
{
    if ($key == "job_payload_hash") {
        $item = $base64String;
    }
}

array_walk_recursive($json, 'update_hash', 'something');

Update

The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:

foreach (array_keys($json['jobs']) as $jobId) {
    $json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}

Upvotes: 3

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..

You can use recursive function lik answer of @Ja͢ck .

Upvotes: 0

i-CONICA
i-CONICA

Reputation: 2379

Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.

Also, use array_key_exists() rather than comparing array key strings.

$array = json_decode($json);

if(array_key_exists("job_payload_hash", $array){
  $array["job_payload_hash"] = base64encode($var);
}

$json = json_encode($array);

Upvotes: -1

goldlife
goldlife

Reputation: 1989

this is because you have to save not in variables you defined after => in a foreach. You have to store this in format:

$json[0][0] ... = $base64String;

OR

You have to add a new array like $result = array() before you write the foreach and then store it in $result.

Upvotes: -1

Related Questions