【问题标题】:How to properly format a JSON array | PHP如何正确格式化 JSON 数组 | PHP
【发布时间】:2023-04-04 06:40:02
【问题描述】:

基本上我有以下数组,其中包含通过函数传递的各种值。然后需要将每个的输出组装成一个 JSON 数组,如下所示:

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

到目前为止的代码:

   <?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);
    }
    
    ?>

如何做到这一点?

【问题讨论】:

  • 总是只有四个值吗?
  • 总是有预设数量的值,是的。 4 只是一个例子。
  • 那个答案有点不清楚。你的意思是总是有相同数量的值,值的数量不会改变?还是您的解决方案需要灵活?
  • 是的,总会有相同数量的值,很抱歉造成混淆。

标签: php json


【解决方案1】:
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:添加了response 嵌套。

【讨论】:

  • 如何在数组开始前获取"response":
  • @StephanieSmith,只需为 $result 值添加带有 response 键的数组嵌套。在更改后的答案中观看。
  • 一个快速的最后一个问题,我怎样才能在末尾添加一个名为responsemessage 的静态嵌套数组,这是为了遵循第一个响应数组。只是做['error' =&gt; false, 'response' =&gt; $result, 'responsemessage' =&gt; 'Response Message'] 是行不通的
  • 示例}, "responsemessage" : { "message": "Response Message"
  • @StephanieSmith,你的意思是['error' =&gt; false, 'response' =&gt; $result, 'responsemessage' =&gt; ['message' =&gt; 'Response Message']]
猜你喜欢
  • 2021-04-24
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
相关资源
最近更新 更多