I have an array that i need to convert to json format
The array is the result of a array_count_values and it looks like this:
(The number of users can change)
array(4) {
["user1"]=>
int(1)
["user2"]=>
int(1)
["user3"]=>
int(1)
["user4"]=>
int(3)
}
and based on that array i need to build a JSON response that must follow this pattern:
$return = [
['username' => 'user1', 'accepted' => 1],
['username' => 'user2', 'accepted' => 1],
['username' => 'user3', 'accepted' => 1],
['username' => 'user4', 'accepted' => 3]
];
echo json_encode($return);
I've tried some "foreach" but i struggle a little with arrays and couldn't get it to work.
You can use a foreach loop to get the keys and values from your array to form the output:
$return = array();
foreach ($array as $key => $value) {
$return[] = array('username' => $key, 'accepted' => $value);
}
echo json_encode($return);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.