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

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']
}

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 Save string and variable to a array

How do I save the string below with the variables to a array? It doesnt seem to work..
$str[] = {'name':'$data['name']','y':$data['values'],'key':'$data['key']'},
$str_str = implode(' ', $str);
echo $str_str;
Thanks.
You should read about basic array and string handling in PHP. Something like this should work:
$str[] = [
'name' => $data['name'],
'y' => $data['values'],
'key' => $data['key']
];
Maybe the best way is just use $str[] = json_encode($data);
Are you trying to save a JSON string into an array?
$var[] saves a value to the first available numeric key in the array $var
The string you would like to save looks like a JSON string, if that's what you want you can do so by:
$var[] = json_encode($data)
If the data array contains the following:
Array
(
[name] => value name
[y] => value y
[key] => value key
)
JSON encoding this array will give you:
{"name":"value name","y":"value y","key":"value key"}

How can I display an array in a readable format?

I want to write my Array into a readable format.
$result = array_diff($one, $two);
print_r($result);
Array ( [1] => 298GS [2] => 09283 [3] => U4235 )
This is how it should look like:
298GS
09283
U4235
My only idea is to write it like this:
echo $result[1];
echo $result[2];
echo $result[3];
But this is not very useful because I never know how many values my array will have.
There isn't much to say, just loop through the array and show the values. This works for variable number of items
foreach($result as $r){
echo $r."<br>";
}
Since you had difficulties doing such thing, I suggest you to study about the basics of the language (IF, lopps, variables, etc) - maybe that's what you are doing, IDK. Foreach and More.
I use the following function as I can read the keys too, the output showed below is what you'll actually see so it is formatted.
function debugArray($arr)
{
return "<pre>" . var_export($arr, true) . "</pre>";
}
$arr = [
1,
2,
3,
4,
5
];
echo debugArray($arr);
Output
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
)
Actual image of output.
You might want to check json_encode to export your data in json format so you can use it better with UI

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);

json_encode children items?

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"));

Categories