how do I get my php array to json - php

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

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.

Create an object from a valid JSON array with php

I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];

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

push array into multidimensional array?

I have json_encoded array that i would like to add to using php
[{"id":"a","value":"2"},{"id":"b","value":"2"}]
I want to add the following to the array above:
array("id" => c, "value" => "3")
I tried json_decode then trying to push the array into that but im confused on how to do that
Make sure you use json_decode in array mode rather than object mode:
// Default: JSON is decoded as object
$json_object = json_decode($json_string);
// Pass true in the second argument to get an array instead
$json_array = json_decode($json_string, true);
// Push a new entry onto the end
$json_array[] = array("id" => c, "value" => "3");
// Re-encode JSON string, if needed
$json_final_string = json_encode($json_array);

Transform string from associative array into multidimensional array

I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.
So my array looks like this:
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
So I'd like to have it in the following form:
$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
"http://localhost/img/second.png" )
);
I haven't been PHP'ing for a while, but for that simple use-case I would use explode.
$array['urls'] = explode(',', $array['urls']);
Uncertain if I interpreted your question correct though?
You can use array_walk_recursive like in the following example.
function url(&$v,$k)
{
if($k=='urls') {
$v = explode(",",$v);
}
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");
You can check the output on PHP Sandbox

Categories