使用json_encode将Array转换为json

时间:2013-08-04 22:18:37

标签: php arrays json foreach

我有一个带有输出(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  ']';

3 个答案:

答案 0 :(得分:0)

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

http://codepad.org/xApWlo7j

答案 1 :(得分: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);

答案 2 :(得分: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被禁用...