0

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?

4
  • Is there always just four values? Commented Dec 25, 2021 at 18:21
  • There is always a preset quantity of values, yes. 4 is just an example. Commented Dec 25, 2021 at 18:22
  • That answer was a bit unclear. Do you mean that there will always be the same amount of values, that the amount of values won't change? Or does your solution need to be flexible? Commented Dec 25, 2021 at 18:25
  • Yes there will always be the same amount of values, sorry for the confusion. Commented Dec 25, 2021 at 18:26

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

5 Comments

How can I get the "response": before the array starts?
@StephanieSmith, just add array nesting with response key for $result value. Watch it in changed answer.
A quick final question, how can I add one more static nested array at the end called responsemessage this is meant to following the first response array. Just doing ['error' => false, 'response' => $result, 'responsemessage' => 'Response Message'] is not working
Example }, "responsemessage" : { "message": "Response Message"
@StephanieSmith, you mean ['error' => false, 'response' => $result, 'responsemessage' => ['message' => 'Response Message']]?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.