push array into multidimensional array? - php

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

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 JSON Encode square bracket

I have a simple JSON array I am trying to encode. Inside of the JSON string I need another array in square brackets. I am unable to figure out how to make the internal brackets square. Any advice?
Here is my code
$data = [ "item" => ["id" => "123456", "name" => "adam"] ];
$data_string = json_encode($data);
Here is the output
{"item":{"id":"123456","name":"adam"}}
What I am hoping to get
{"item":["1123","1134","1184"]}
In JSON [] is an array and {} is an object.
An array holds an ordered list of values.
An object holds an unordered group of key / value pairs.
If you want an array, then you have to provide an ordered list of values (a PHP array) and not a set of key / value pairs (a PHP associative array).
$data = [ "item" => ["id", "123456", "name", "adam"] ];
$data_string = json_encode($data);
gives
{"item":["id","123456","name","adam"]}
As I remember, JSON array can not have keys and values at the same time, as for javascript. If you have php array with keys and values, that will be converted to Object for JSON, remove keys from php array and you will get JSON array too.

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_decode() expects parameter 1 to be string, array given?

this is my data ,After Json_encode()
Array
(
[{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}]
=>
)
now i want to decode it back ,by applying json_decode() it gives the following error
json_decode() expects parameter 1 to be string, array given
any idea sugestion what to do ?
Your json must be in string, not in array
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_array = json_decode($json_string);
$json_array : ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
If your json is in array you can do :
$json_string_in_array = ['{"a":1,"b":2,"c":3,"d":4,"e":5}'];
$json_array = json_decode($json_string_in_array[0]);
json_encode() returns a string, so I don't know how you can be getting an array out of it unless you are storing it in an array yourself like:
$json = [];
$json[] = json_encode($someArray);
Instead, just store it in a non-array variable:
$jsonString = json_encode($someArray);
Then you can decode it like this:
$decodedArray = json_decode($jsonString);
$jsonstr = '[{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}]';
$ar = json_decode($jsonstr,true); # json string to Array
$obj = json_decode($jsonstr); # json string to Object
var_dump($ar,$obj);

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

Categories