json_encode children items? - php

How can I use php json_encode to produce the following from an array?
{"issue":{"project_id":"Test Project","subject":"Test Issue"}}
I've been trying for the last 40 mins but I can't get it working for the life of me.
The best I can do is:
$arr = array ("project_id"=>"Baas","subject"=>"Test Issue");
echo json_encode($arr); // {"project_id":"Baas","subject":"Test Issue"}
The problem is making "issue" parent. Any hint on how to accomplish this?
Thanks!

The output you want is essentially an associative array nested in another associative array. So, create that data structure, then encode it.
$child_arr = array("project_id" => "Baas", "subject" => "Test Issue");
$parent_arr = array("issue" => $child_arr);
echo json_encode($parent_arr);
Or, if we're in a one-liner mood today:
$arr = array("issue" => array("project_id" => "Baas", "subject" => "Test Issue"));
echo json_encode($arr);

$arr = array ("issue" => array("project_id"=>"Baas","subject"=>"Test Issue"));

Related

Cannot iterate over array after json_decode(file_get_contents(filename))

I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong?
var_dump() shows the array.
<?php
$array = array(
array("Artikel" => "Bananen",
"Menge" => 10,
"id" => "4711"
),
array("Artikel" => "Eier",
"Menge" => 1,
"id" => "abc"
)
);
file_put_contents("daten.json", json_encode($array));
$array1 = json_decode(file_get_contents("daten.json"));
var_dump($array1);
for($i=0; $i<count($array1); $i++){
echo $array1[$i]["Menge"];
echo "<br>";
}
?>
If you run your code, you will get the error Cannot use object of type stdClass as array.
This is because when json_encode is executed, the nested arrays are interpreted as an objects.
If you write:
$array1 = json_decode(file_get_contents("daten.json"), true);
then the objects will be converted to arrays and everything will work as expected.

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

php make a json object not working as expected

This is my code:
$amenitiesObject = array('parameter-amenities' => array('value' => $amenities));
$buildingObject = array('parameter-building' => array('value' => $building));
$data = array($amenitiesObject, $buildingObject);
$post_data = json_encode($data, JSON_FORCE_OBJECT);
return $post_data;
the result is:
{"0":{"parameter-amenities":{"value":""}},"1":{"parameter-building":{"value":""}}}
while i was hoping for this:
{"parameter-amenities":{"value":""},"parameter-building":{"value":""}}
what is my mistake please?
While #fusion3k's comment is correct and doing $data = array_merge( $amenitiesObject, $buildingObject ); fixes it, I'd like to explain it a little further so you can avoid this type of scenario.
When you do $data = array($amenitiesObject, $buildingObject);, you are not creating a merge of both arrays, you are creating an array with index 0 equals to $amenitiesObject and index 1 equals to $buildingObject, the equivalent of doing :
array(0 => $amenitiesObject, 1 => $buildingObject);
So the json_encode part is working as expected.
When you use array_merge, you maintain only ONE array, that is a combination on both arrays, so you have the expected result.

how do I get my php array to json

I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);

Converting a multi-dimensional php array into a JSON array of objects

I need to create a multi-dimensional array in php and want to use it in a jQuery script as a JSON array of objects;
The required output in the jQuery script should look like this:
data = [
{ Month:'April', Comms:1000, Fees:200, Gains: 200},
{ Month:'May', Comms:1200, Fees:300, Gains: 300}
]
Currently my php arrays are generated as follow:
$data1[] = array(
'Month' => 'April',
'Comms' => 1000,
'Fees' => 200,
'Gains' => 200
);
$data2[] = array(
'Month' => 'May',
'Comms' => 1200,
'Fees' => 300,
'Gains' => 300
);
echo json_encode($data);
My question is how to combine data1 and data2 into the data array in the json_encode php function which will produce the required jQuery JSON array of objects?
I do have the values of the different array fields and can create data1 and data2 in a different way, so the data is flexible and I can combine them in any other way which will produce the data array which will output them in the required JSON format.
Any help will be highly appreciated, I have seen question regarding this subject but none which address the issue I am facing.
Simply:
echo json_encode($data1 + $data2);
Note that you can also use + to merge arrays.
You'll want to merge both Arrays into a new Array of Arrays. See the manual for more information.
$data = array_merge($data1, $data2);
echo json_encode($data)
or, more simply by using the + operator:
echo json_encode($data1 + $data2)
Try :
echo json_encode(array_merge($data1, $data2));
Write:
echo json_encode($data1 + $data2);
just user
echo json_encode($data1 + $data2);
You should make another array by extracting data from database by using groupBy months and store the data in other array.
$array = array();
foreach ($data as $element) {
$array[$element['month']][] = [ 'comms' => $element['comms'], 'fees' => $element['fees'], 'gains' => $element['gains']
}

Categories