I am trying to get results when converting a url to json. I thank those who can help me, thank you.
I have this string: id_user123=123;456;789&id_user456=333;545;908
I would like to get this result:
{"result": [
{"id_user123":[ "123", "456", "789" ] },
{"id_user456":[ "333", "545", "908" ] }
]}
Use parse_url to get the "query" part of your string
and parse_str to get each parameter and values.
<?php
$url = 'test.php?id_user123=123;456;789&id_user456=333;545;908';
parse_str(parse_url($url, PHP_URL_QUERY), $queryArray);
$result = [];
foreach ($queryArray as $userId => $values) {
$result['result'][] = [
$userId => explode(';', $values)
];
}
echo "<pre>";
echo json_encode($result, JSON_PRETTY_PRINT);
echo "</pre>";
will output
{
"result": [
{
"id_user123": [
"123",
"456",
"789"
]
},
{
"id_user456": [
"333",
"545",
"908"
]
}
]
}
Simple loop with explode():
$result = ['result' => []];
foreach ($_GET as $userId => $values) {
$result[] = [
$userId => explode(';', $values);
];
}
echo json_encode($result);
Related
I have the code below, but the result of the json response doesn't match
public function tes_get(){
$kode= $this->M_mymodel->tbl_kode('302'); // row
$res = array();
foreach ($kode as $key=> $value) {
$win = $this->M_mymodel->db_aa('302'); //row_array
$res = $this->M_mymodel->db_bb('302','LOSE'); //row_array
$res['data'][] = array(
'win' => $win['menang'],
'lose' =>$res['kalah']
);
}
$response = $this->set_response($res,200);
}
Below is the result of the response from the code I made above
{
"data": [
{
"win": "2",
"lose": "11"
}
]
}
How to make json response like below?
{
"data": [
{
"win": "2",
}
{
"lose": "11"
}
]
}
You can try :
$res['data'][] = array(
array('win' => $win['menang']),
array('lose' =>$res['kalah'])
);
I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])
I have a simple bit of JSON like this:
{
"grinning": {
"unicode": "1f600",
"unicode_alternates": "",
"name": "grinning face",
"shortname": ":grinning:",
"category": "people",
"emoji_order": "1",
"aliases": [
],
"aliases_ascii": [
],
"keywords": [
"happy",
"joy",
"smile",
"grin",
"smiling",
"smiley",
"person"
]
},
"grimacing": {
"unicode": "1f62c",
"unicode_alternates": "",
"name": "grimacing face",
"shortname": ":grimacing:",
"category": "people",
"emoji_order": "2",
"aliases": [
],
"aliases_ascii": [
],
"keywords": [
"teeth",
"grimace",
"disapprove",
"pain",
"person"
]
}
}
I can access the "unicode" and "name" elements via:
<?php
$str = file_get_contents('http://localhost/_testing/emoji/emoj1-test.json');
$json_a = json_decode($str, true);
foreach($json_a as $key => $val) {
echo $val['unicode'];
echo $val['name'];
}
?>
But I can't work out how I can get the "keywords" nested array into a variable containg the keywords held as a comma separated list of values.
I simplistically tried:
echo $val['keywords'];
But because that's an array, it returns this error:
Notice: Array to string conversion
I then tried:
echo $val['keywords'][0];
Which I think is along the right lines, but still doesn't return any data.
echo implode(',', $val['keywords']);
Try with join,
foreach($json_a as $key => $val){
echo join(", ", $val['keywords']);
}
The following works up to 2 levels of nesting. You can iterate and print the entire nested array with it.
<?php
$arr = ['Your JSON'];
foreach ($arr as $key => $value) {
$string = is_array($value) ? implode(",", $value) : $value;
echo $string;
}
?>
Here's what I want to do in my php array to be exact json format below:
JSON
{
"suggestions": [
{ "value": "Alex - alex#email.com", "data": {"id": 1, "name": Alex } },
{ "value": "John - john#email.com", "data": {"id": 2, "name": John } },
{ "value": "Diaz - diaz#email.com", "data": {"id": 3, "name": Diaz } }
]
}
Query result in my php array:
array(
0 => array('id'=>'1' 'email'=>'alex#email.com', 'name'=>'Alex'),
1 => array('id'=>'2' 'email'=>'john#email.com', 'name'=>'John'),
2 => array('id'=>'3' 'email'=>'diaz#email.com', 'name'=>'Diaz')
);
Do you have any idea how will you make my php array to that JSON format way?
You can simply use json_encode(); function for that.
json_encode($array);
This should help you for your JSON format
foreach($query as $key => $val){
$json[$key]['value'] = $val['name']." - ".$val['email'];
$json[$key]['data']["id"] = $val['id'];
$json[$key]['data']["name"] = $val['name'];
}
echo json_encode($json);
foreach ($your_array as $key => $val) {
foreach ($val as $k => $v) {
if ($v == 'email') {
//get the value of 'email' key in 'value'
$newArr['suggestions']['value'] = current($v);
}
else {
//if value is not email push it in 'data' key
$newArr['suggestions']['data'] = $v;
}
}
}
//lastly encode the required array
echo json_encode($newArr);
in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>
You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO