Home > Net >  How to properly format a JSON array | PHP
How to properly format a JSON array | PHP

Time:12-26

Essentially I have the following array with various values that are being passed through a function. The output of each needs to then be assembled into a JSON Array that looks like the following:

  "response": {
    "firstvalue": 4,
    "secondvalue": 1,
    "thirdvalue": "String Response 1",
    "fourthvalue": "String Response 2"
  }

Code So Far:

   <?php
    header('Content-Type: application/json');
    
    $arrayvalues = 
    ["34jkw9k2k9w", 
    "k4otk320el01oeoo20", 
    "30f0w2l020wk3pld==", 
    "3c2x3123m4k43=="];
    
    foreach($arrayvalues as $item) {
        $decrypted = myFunction($item, $action = 'decrypt');
        $response["firstvalue"] = $decrypted;
        $response["secondvalue"] = $decrypted;
        $response["thirdvalue"] = $decrypted;
        echo json_encode($response);
    }
    
    ?>

How can this be done?

CodePudding user response:

header('Content-Type: application/json');

$arrayvalues = 
["34jkw9k2k9w", 
"k4otk320el01oeoo20", 
"30f0w2l020wk3pld==", 
"3c2x3123m4k43=="];


// Is this necessary?
$keys = ['firstvalue', 'secondvalue', 'thirdvalue', 'fourthvalue'];

$result = [];
foreach($arrayvalues as $idx => $item) {
    $result[$keys[$idx]] = myFunction($item, $action = 'decrypt');
}

echo json_encode(['response' => $result], JSON_PRETTY_PRINT);

UPD: Added response nesting.

  • Related