I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;
Related
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 am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)
How do I create a JSON like this with PHP? I am trying to convert a dynamic data and save it into a MySQL database.
{
"fbd49440-a5a1-48be-b13e-e8efddad3588": {
"0": {
"value": "dsfrasdf5464356dfs hdhfg dfgh"
}
},
"0fc71cea-5609-40a7-a1d2-b78139660f8f": {
"0": {
"value": "50"
}
},
"73936e70-4329-4aba-b47c-42c64ced420c": {
"0": {
"file": "\/components\/com_djclassifieds\/images\/item\/25_juliet_ibrahim.jpg",
"uniqid": "59a352b96773325",
"title": "",
"file2": "",
"overlay_effect": "",
"caption": "",
"width": "",
"height": ""
},
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6": {
"0": {
"value": "members-in-good-standing-2014",
"text": "",
"target": "0",
"custom_title": "",
"rel": ""
}
},
"69072346-fe4c-489e-8e2b-5a7d7409fd44": {
"0": {
"value": "34"
}
}
}
I tried the code below but it did not give me the result I want.
$json = (
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> (
$array1
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> (
$array2
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> (
$array3
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> (
$array4
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> (
$array5
)
)
echo json_encode($json);
I will be glad if someone could help me, thank you
json_encode will take multiple types of valid data and try to encode them into a json representation of it. It does require that the input is valid.
The code you have pasted has multiple syntax errors, and we cannot tell what is in your $array1. $array2, $array3, $array4, $array5. However a couple of changes (and assuming your $arrays are actual arrays) has your code working.
There are also bitmask options in the form of JSON Constants that will define how your JSON should be stored.
$array = array( "data" => "value"); // dummy array to show data working
$json = array( //defined the following as an array
"fbd49440-a5a1-48be-b13e-e8efddad3588"=> array( //notice each of these are now defined as arrays
$array
),
"0fc71cea-5609-40a7-a1d2-b78139660f8f"=> array(
$array
),
"73936e70-4329-4aba-b47c-42c64ced420c"=> array(
$array
),
"ac00b95e-9eeb-4035-bf4a-ff206319b2d6"=> array(
$array
),
"69072346-fe4c-489e-8e2b-5a7d7409fd44"=> array(
$array
)
); //added semicolon to end the declaration
echo json_encode($json, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) );
// added JSON_FORCE_OBJECT and JSON_PRETTY_PRINT
// As bitmask options, they return a constant to give `json_encode` instructions
// JSON_FORCE_OBJECT => 16, JSON_PRETTY_PRINT => 128
// JSON_FORCE_OBJECT + JSON_PRETTY_PRINT = 16 + 128 = 144
// json_encode( $array, ( JSON_FORCE_OBJECT + JSON_PRETTY_PRINT ) = json_encode ($array, 144);
Returns
{"fbd49440-a5a1-48be-b13e-e8efddad3588":{"0":{"data":"value"}},"0fc71cea-5609-40a7-a1d2-b78139660f8f":{"0":{"data":"value"}},"73936e70-4329-4aba-b47c-42c64ced420c":{"0":{"data":"value"}},"ac00b95e-9eeb-4035-bf4a-ff206319b2d6":{"0":{"data":"value"}},"69072346-fe4c-489e-8e2b-5a7d7409fd44":{"0":{"data":"value"}}}
Array of Arrays in your json data.
If you want it to print the index of each result, that needs to be treated as an array as well. Simple enough to understand when there are multiple pairs in the result, less intuative when the result is one pair.
$array1 = array( "data" => "value");
echo json_encode($array1, JSON_FORCE_OBJECT );
//would return
//{"data":"value"}
$array2 = array(
array( "data" => "value" ),
array( "data" => "value" )
);
echo json_encode($array2, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"},"1":{"data":"value"}}
$array3 = array(
array( "data" => "value" )
);
echo json_encode($array3, JSON_FORCE_OBJECT );
// would return
// {"0":{"data":"value"}}
I'm trying to put an array inside an array (inside an array) using PHP.
$objectArray = array ('id' => $place, 'name'=>$placeName, array ('contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)));
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;
This gives me something like this:
{
"place": {
"0": {
"contact_info": {
"phone": "513-555-1212",
"email": "jmr#example.com",
"website": "https://example.com"
}
},
"id": "999999",
"name": "My House",
}
}
What I'm looking for as an end product is:
{
"place": {
"contact_info": {
"phone": "513-555-1212",
"email": "jmr#example.com",
"website": "https://example.com"
},
"id": "999999",
"name": "My House",
}
I need to not have the '0' and the contact info part under place
For your purposes $objectArray should have this structure:
$objectArray = array (
'id' => $place,
'name'=>$placeName,
'contact_info'=> array ('phone'=>$phone, 'email'=>$email,'website'=>$website)
);
So, contact_info should be on the same level as id and name, without new array.
You need something like this
$objectArray = array (
'id' => '99999',
'name'=>'My House',
'contact_info' => array (
'phone'=>'513-555-1212',
'email'=>'jmr#example.com',
'website'=>'https://example.com'
)
);
$data3 = array('place' => $objectArray);
$data_json = json_encode($data3);
echo $data_json;
Remove the array part placed before 'contact_info' so they come at same level.
I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/