Convert Array to json with json_encode

I have an array with the output (print_r):

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

I need to convert it to a json of this format:

[{"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}] 

This is what I've tried but I'm just guessing and not getting the right output :

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

Answers


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

http://codepad.org/xApWlo7j


Try this:

$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);

Code

$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);

Result

[{"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}]

I tried to link my example here: http://sandbox.onlinephpfunctions.com/, but the share CAPTCHA is disabled...


Need Your Help

SOAP POST method performs GET?

java web-services post soap get

I have a SOAP webservice that is currently POST method, however I saw on my logs that when client is consuming my service there are two calls being made, 1 is to GET the wsdl file then POST to the

Html loaded via ajax is not working with jQuery events

ajax html5 jquery

I've this code in a file called checkout.tpl, also have a Javascript code and I'll comment below:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.