PHP JSON Encode square bracket - php

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.

Related

Create payload from array

I am trying to create the payload/data using an PHP array as input, by using [json_encode]. I noticed that the results of payload_1 has squared brackets but that payload_2 does not.
Question:
How can I create payload_2 with the result of squared brackets in the same position as in payload_1 ? To clarify, the outcome of payload_2 should be same as outcome of payload_1.
<?php
// Create payload from string.
$payload_1 = "{
\"prenumeration\":
[
{
\"url\":\"http://www.google.com\"
}
]
}";
var_dump($payload_1);
echo "\n\n";
// Create payload from array.
$payload_2 = array(
"prenumeration" => array(
"url" => "http://www.google.com"
)
);
$payload_2 = json_encode($payload_2);
var_dump($payload_2);
echo "\n\n";
Results:
Result (payload_1):
"{"prenumeration":[{"url":"http://www.google.com"}]}"
Result (payload_2):
"{"prenumeration":{"url":"http:\/\/www.google.com"}}"
Try the following:
$payload_2 = array(
"prenumeration" => array(array(
"url" => "http://www.google.com"
))
);
prenumeration must be an array of associative arrays.
array("url" => "http://www.google.com") is an associative array of one element. Associative arrays are represented with curly brackets.
array(array("url" => "http://www.google.com")) is an array of one element (that happens to be an associative array). Arrays are represented with square brackets.

PHP convert array to serialized string suitable as an array key

I have several associative arrays in PHP that looks like this:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
I want to create another associative array, using the serialized values of the previous arrays are used as the array keys. For example:
$newArray = array("data1's serialized key" => "someNewValue", ... );
Are serialized arrays suitable for being used as array keys?
Do they contain any unacceptable characters?
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Are serialized arrays suitable for being used as array keys?
Yup! As far as I know you can use serialized arrays as a key in another array. But the I cannot think of any use-case for this. :P
Do they contain any unacceptable characters?
No, until and unless you specify any unacceptable characters in the original array.
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Nope.
So, you code would look like:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);

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

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

Prevent json_encode() from automatically generating integer keys

I'm trying to encode a two-dimensional PHP array to JSON with json_encode() and I'm having a problem:
My array looks like this:
$array = array( array( 1325368800, 6898 ) );
When I encode it to JSON using json_encode(), the output looks like this:
'data' : [
'0' : [ '0' : '1325368800', '1' : '6898' ]
]
I would like to get rid of the automatically generated integer keys and have it like this:
'data': [ [ '1325368800', '6898' ] ]
Any tips?
This can only happen if you give the JSON_FORCE_OBJECT flag to json_encode (live demo):
echo json_encode(array(array( 123, 123 )));
// outputs [[123,123]]
echo json_encode(array(array( 123, 123 )), JSON_FORCE_OBJECT);
// outputs {"0":{"0":123,"1":123}}
Make sure the second argument of json_encode is not set, or set to a value generated by ORing JSON_* constants together.
If, however, the data is an associative array, you can use array_values to get a JSON array instead of a JSON object:
$assocData = array('0' => array('0' => 123, '1'=>123));
$arrayData = array_map('array_values', array_values($assocData));
echo json_encode($arrayData);
By the way, the JSON output you cited is invalid, since it uses square brackets ([]) for objects, and misses a quote after "0.

Categories