1

我有一个输出数组(print_r):

Array
(
[a] => 706
[b] => 194
[c] => 164
[d] => 44
[e] => 42
[f] => 41
[g] => 40
[h] => 38
[i] => 13
)

我需要将其转换为这种格式的 json:

[{"name":"a","value":706},{"name":"b","value":194},{"name":"c","value":164},{"name":"d","value":44},{"name":"e","value":42},{"name":"f","value":41},{"name":"g","value":40},{"name":"h","value":38},{"name":"i","value":13}] 

这是我尝试过的,但我只是猜测并没有得到正确的输出:

 echo  '[';
foreach($sortedArray as $key => $value) {
echo  $dataTable = json_encode(array(
    'name' => $key,
    'value' => $value
), JSON_NUMERIC_CHECK);
};
 echo  ']';
4

3 回答 3

0
$keyPair = array();
foreach($sortedArray as $key => $value) {
  $keyPair[] = array('name' => $key, 'value' => $value);
}
echo json_encode($keyPair);

http://codepad.org/xApWlo7j

于 2013-08-04T22:26:06.820 回答
0

尝试这个:

$data = array(
  'a' => 234, 'b' => 2343, 'c' => 23423, /* etc. */
);

$new_data = array();
foreach ($data as $k => $v) {
  $new_data[] = array(
    'name' => $k, 'value' => (number)$v
  );
}

print json_encode($new_data);
于 2013-08-04T22:26:14.447 回答
0

代码

$arr = array(
  'a' => 706,
  'b' => 194,
  'c' => 164,
  'd' => 44,
  'e' => 42,
  'f' => 41,
  'g' => 40,
  'h' => 38,
  'i' => 13);

$map_arr = array();
foreach ($arr as $k => $v)
  $map_arr[] = array('name' => $k, 'value' => intval($v));

print json_encode($map_arr);

结果

[{"name":"a","value":706},{"name":"b","value":194},{"name":"c","value":164},      
{"name":"d","value":44},{"name":"e","value":42},{"name":"f","value":41},
{"name":"g","value":40},{"name":"h","value":38},{"name":"i","value":13}]

我试图在此处链接我的示例:http: //sandbox.onlinephpfunctions.com/,但共享 CAPTCHA 已禁用...

于 2013-08-04T22:33:06.917 回答