I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format
Related
I'm learning OOP and I whould create a list of objects in an array, but my code return the last array
I have search here, but haven't found a solution or idea how to do this.
Excepct
"MerchantDefinedFields":[
{
"Id":2,
"Value":"email#test.com"
},
{
"Id":4,
"Value":"Web"
},
{
"Id":9,
"Value":"NAO"
},
{
"Id":83,
"Value":"Field"
},
{
"Id":84,
"Value":"Only"
}
]
My code
$MDDs = array(
array("Id" => 2, "Value" => "email#test.com"),
array("Id" => 4, "Value" => "Web"),
array("Id" => 9, "Value" => "NO"),
array("Id" => 83, "Value" => "Field"),
array("Id" => 84, "Value" => "Only")
);
foreach($MDDs as $MDD){
$abac = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
Result
Array
(
[Id] => 84
[Value] => PROPRIO
)
Your foreach() is re-setting $abac every time it goes through the loop. So on the last time it runs, it will set the variable to the last item in your array.
Instead of setting the variable each time, try adding the key->value to an array (or something like that, depending on what you want):
$abac = [];
foreach($MDDs as $MDD){
$abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
It's hard to create the exact right answer for you, since it's unclear what you're trying to accomplish, but this should at least point you in the right direction.
For simple answer :- You don't need foreach loop to get the desired result
you can simply use built-in php function to convert your array to JSON
$abac = json_encode ( $MDDs);
Now coming to your problem :-
you are re-assigning the $abac variable in loop instead of adding values to it like .
$abac = [];
foreach($MDDs as $MDD){
$abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}
The best way to do it is to declare the $abac outside of the foreach and then use the array_push method like this:
$abac = array();
foreach($MDDs as $MDD)
{
array_push($abac, array("Id" => $MDD['Id'], "Value" => $MDD['Value']));
}
print_r($abac);
My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.
Up until now I have just used PHP's json_encode() on simple rows of data, for example
{
"name":"bob",
"age":"22"
}
However I have the need to return JSON which has arrays.
Example output is
{
"success":true,
"payload":
{
"venuedata":
{
"id":"1",
"name":"venue name"
},
"menus": [
{"menuid":"1","menuname":"food","items": [{"item":"pizza","cost":"$12.50"},{"item":"burger","cost":"$14.50"}]},
{"menuid":"2","menuname":"drinks","items": [{"item":"pint of beer","cost":"$5.50"}]}
]
}
}
Now, the venuedata object will come from one PDO query, and the menus will come from another query and the items for each menu will come from another query.
How can I use json_encode to return the example JSON?
A generalized example assuming the menu items and the menus are connected to each other with a foreign key.
Create an array of menus and add for every menu element in the array the menu items.
$arrMenus = array();
$menus = getMenusFromDB();
foreach($menus as $menu) {
$menuItems = getMenuItemsFromDB($menu["id"]);
$arrMenuItems = array();
foreach($menuItems as $menuItem){
$arrMenuItems []= array(
"item" => $menuItem["item"],
"cost" => $menuItem["cost"]
);
}
$arrMenus []= array(
"menuid" => $menu["id"],
"menuname" => $menu["menuname"],
"items" => $arrMenuItems
);
}
Then create an array with the rest of the information and add the "menus" array as part of the "payload" array:
$obj = array(
"success" => true,
"payload" => array(
"venuedata" => array(
"id" => "2",
"name" => "venue name"
),
"menus" => $arrMenus
)
)
After convert the array via json_encode():
$json = json_encode($obj);
I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);
I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);