从PHP中的结果准备json数组

时间:2019-01-23 07:22:06

标签: php arrays json

我正在为每个循环数组并准备json数组,如下所示。

$resultArr = array();
$paramArr = array();
$Items = [];
$Items [] = ['value' => 17];
$Items [] = ['value' => 18];
$Items [] = ['value' => 19];
$Items [] = ['value' => 20];
$Items [] = ['value' => 21];
$Items [] = ['value' => 22];

foreach ($Items as $key => $item) {

  $paramArr['key'] = $key;
  $paramArr['value'] = $item;
  json_encode($paramArr);   
}
  $resultArr  = "Success";
  $resultArr['Parameters'] = $paramArr; 

上面的代码给了我如下结果。

   {
   "result": "Success",
    "Parameters": {
       "key": "Gentet",
       "value": "27"
    }
  }

但是我希望输出如下。

   {
   "result": "Success",
    "Parameters": {
       "key": "Gentet",
       "value": "22"
    },
    "Parameters": {
       "key": "Gentet",
       "value": "21"
    }, and etc..
  }

我需要执行什么代码更改才能获得如上所述的输出

3 个答案:

答案 0 :(得分:1)

您需要循环推动Parameters

$resultArr = array();
$paramArr = array();
$Items = [];
$Items [] = ['value' => 17];
$Items [] = ['value' => 18];
$Items [] = ['value' => 19];
$Items [] = ['value' => 20];
$Items [] = ['value' => 21];
$Items [] = ['value' => 22];
$resultArr['result']  = "Success";
foreach ($Items as $key => $item) {
  $paramArr['key'] = $key;
  $paramArr['value'] = $item;
  $resultArr['Parameters'][] = $paramArr;  // Push it here
}

您是在循环完成运行后将其推入的。

因此,只有最后一个元素被推入其中。

答案 1 :(得分:1)

请尝试以下代码

$resultArr = array();
$paramArr = array();
$data=array():
$Items = [];
$Items [] = ['value' => 17];
$Items [] = ['value' => 18];
$Items [] = ['value' => 19];
$Items [] = ['value' => 20];
$Items [] = ['value' => 21];
$Items [] = ['value' => 22];

foreach ($Items as $key => $item) {

  $paramArr['key'] = $key;

  $paramArr['value'] = $item;

  array_push($data,$paramArr);   
}


$resultArr  = json_encode("Success","Parameters"=>$data);

答案 2 :(得分:1)

下面的代码一定可以解决您的问题

$resultArr = $paramArr = [];
$paramJson = '';
$Items = ['key1' => 17, 'key2' => 18, 'key3' => 19, 
                   'key4' => 20, 'key5' => 21, 'key6' => 22];

foreach ($Items as $key => $item) {
  $paramArr[] = ['key' => $key, 'value' => $item]   
}
if (!empty($paramArr)) {
  $resultArr['result']  = "Success";
  $paramJson = json_encode($paramArr);
} else {
  $resultArr['result']  = "Fail";
}
$resultArr['Parameters'] = $paramJson; 

print_r($resultArr); 

它将打印这样的结果

{
  "result":"Success",
  "parameters":
[
   {
     "key":"key1",
     "value":17
   },
   {
     "key":"key2",
     "value":18
   },
   {
    "key":"key3",
    "value":19
   },
  {
    "key":"key4",
    "value":20
  },
  {
    "key":"key5",
    "value":21
  },
  {
    "key":"key6",
    "value":22
  }
]
}

谢谢