PHP json_encode - create JSON array - php

I've used the json_encode function in the past to create simply JSON objects like this:
$payload = array ("user" => $username, "password" => $password, "group" => $group);
$payload = json_encode ($payload);
which creates this:
{"user":"john smith","password":"abc12345","group":"sales"}
I now need to generate a JSON array like this:
{
"query": [
{
"Date": "11/01/2017...12/31/2017"
}
]
}
but I can't find the correct syntax.

You can simply create a 2d array in php.
$payload = array (
"query" => array(
array(
"date" => "11/01/2017...12/31/2017",
"other sub key" => "other sub value"
)
),
"other main key" => array(
array(
"other sub key" => "other sub value",
etc...
)
)
);

That would be something like this
$array = array(
'query' => array(
array('Date' => '11-01-2017')
)
);
echo '<pre>';
print_r(json_encode($array, JSON_PRETTY_PRINT));
Result
{
"query": [
{
"Date": "11-01-2017"
}
]
}

$payload = json_encode($payload, JSON_PRETTY_PRINT);
reference: http://php.net/manual/en/function.json-encode.php

Related

PHP create value variable for json_encode function

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:
$data = '
{
"function":"setArticleImages",
"paras":{
"user":"'.$user.'",
"pass":"'.$pass.'",
"product_model":"'.$productsModel.'",
"images":{
"products_id":'.$products_id.',
"image_name":"'.$imageName.'",
"image":"'.$image.'",
"products_images":[{
"products_id":'.$products_id.',
"image_name":"'.$imageName2.'",
"image":"'.$image2.'"
} ]
}
}}
';
I was now trying to write it like this and use json_encode:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
),
)
)
);
$data = json_encode($data);
Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.
Anyone an idea how to write it in the second code snippet?
You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:
$data = array(
"function" => "setArticleImages",
"paras" => array(
"user" => $user,
"pass" => $pass,
"product_model" => $productsModel,
"images" => array(
"products_id" => $products_id,
"image_name" => $imageName,
"image" => $image,
"products_images" => array(
array(
"products_id" => $products_id,
"image_name" => $imageName2,
"image" => $image2,
)
),
)
)
);
Demo on 3v4l.org
The "{ }" in th JSON notation is a PHP array with alphanumerical key.
So :
$array = ["foo" => [1,2,3], "bar" => [4,5,6]
will be converted in a JSON string :
{ foo : [1,2,3], bar: [4,5,6]}
So if you are looking to a JSON that looks like this
[{ foo : [1,2,3], bar: [4,5,6]}]
You will have to do an array with numeric keys that contains your alphanumerical array :
$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

Remove from multidimensional array if has seen id before in an basic array

I would like in php to stop duplicate messages by logging msgid to a text file using something like this file_put_contents("a.txt", implode(PHP_EOL, $array1), FILE_APPEND);
and then converting it back to an array using $array1 = file("a.txt"); I would also like to delete messages from the array if they are from a set name
I know how to convert json to an array $array1 = json_decode($json, true);
Json Reply from an api that I cannot control
{
"API": "Online",
"MSG": [
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
},
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
}
]
}
Hi use the following code, first test it out accordingly
$uniqueMessages = unique_multidim_array($messages,'msg');
Usage : Pass the key as the 2nd parameter for which you need to check the uniqueness of array.
<?php
/* Function to handle unique assocative array */
function unique_multidim_array($array, $key) {
/* temp array to hold unique array */
$temp_array = array();
/* array to hold */
$i = 0;
/* array to hold the key for unique array */
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$messages = array(
0 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
),
1 => array(
'info' => array(
'name' => 'example 1'
),
'msg' => 'example 1',
'msgid' => 'example 1'
),
3 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
)
);
echo '<pre>';
echo '*****************BEFORE***********************<br/>';
var_dump($messages);
echo '*****************AFTER***********************<br/>';
$uniqueMessages = unique_multidim_array($messages,'msg');
var_dump($uniqueMessages);
This works for me this is an modded function click here for original function
function RemoveElementByArray($array, $key, $seen){
foreach($array as $subKey => $subArray){
if(in_array($subArray[$key], $seen)){
unset($array[$subKey]);
}
}
return $array;
}
Example:
$array = array(
array("id" => "1", "name" => "example1"),
array("id" => "2", "name" => "example2"),
array("id" => "3", "name" => "example3"));
$SeenArray = array("1", "2");
print_r(RemoveElementByArray($array, "id", $SeenArray));
Result:
Array
(
[2] => Array
(
[id] => 3
[name] => example3
)
)

How can I recreate this JSON array in PHP?

I have an array in JSON that I need to recreate in PHP.
{
"items": {
"category": "fruit",
"detail": [
{
"name": "apple",
"good": true
}
]
}
"moreItems": {
"category": "fruit",
"detail": [
{
"name": "banana",
"good": false
}
]
}
}
My hopes are to create this using PHP arrays, then json_encode it.
I've tried to set the array above to a string, and de_coded it, but I'm not getting anywhere.
Thanks.
in PHP
$arr = array("items" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "apple", "good" => true )
)
),
"moreItems" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "banana", "good" => false)
)
)
);
or for manual assignment that maybe useful if using loops:
$arr["items"]["category"] = "fruit";
$arr["items"]["detail"][0]["name"] = "apple";
$arr["items"]["detail"][0]["good"] = true;
$arr["moreItems"]["category"] = "fruit";
$arr["moreItems"]["detail"][0]["name"] = "banana";
$arr["moreItems"]["detail"][0]["good"] = false;
echo json_encode($arr);
will give you the same output..
Actual output in JSON
Cheers!
If you have a json (in PHP) as a string, and you want to convert them to a native PHP array you can easy do that:
<?php
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$json = '{\
"items": {\
"category": "fruit",\
"detail": [\
{\
"name": "apple",\
"good": true\
}\
]\
}\
"moreItems": {\
"category": "fruit",\
"detail": [\
{\
"name": "banana",\
"good": false\
}\
]\
}\
}';
$array = objectToArray( json_decode($json) );
echo "<pre>".print_r($array, true)."</pre>";
That's it!
Thanks to Michael Berkowski, this worked for me. You can recreate the nested [] in the code below.
If you want to replicate the structure more truly, forcing PHP to use
stdClass objects instead of assoc arrays, you might cast the inner
ones to objects: 'detail' => array(0 => (object)array('name' =>
'banana', 'good' => false))
This below will do just fine for me.
$phpArray = array(
"items" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "apple", "good" => true
)
)
),
"moreItems" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "banana",
"good" => false
)
)
)
);

Converting php object to json

I've a php object that I want to convert to the following json format.
All the data values are object via a php object in the format:
Array ( [0] => stdClass Object ( [id] => 2
[s1] => 1485
[name] => 1485
[credit] => ''
[caption] => ''
)
)
I'm trying to group the credit, caption, etc. under child. Also, I'm unable to get the [ after date in the json format.
{
"mydata":
{
"name":Name,
"type":"default",
"date": [
{
"s1":"1485",
"name":"1485",
"child":
{
"credit":"",
"caption":""
}
}]
}
}
Currently, my code looks like:
foreach ($hits as $hit) {
$data->mydata->date->s1 = $hit->s1;
$data->mydata->date->name = $hit->name;
$data->mydata->date->credit = $hit->credit;
$data->mydata->date->caption = $hit->caption;
}
$a = json_encode($data);
set $date->mydata->date to an array and you will get the []
And why not making more nested structures?
The JSON format you're looking at shows that date is an array (the brackets are array notation in javascript), so:
<?php
$var = array(
'mydata' => array(
'name' => 'Name',
'type' => 'default',
'date' => array(
array(
's1' => 1485,
'name' => '1485',
'child' => array(
'credit' => '',
'caption' => '',
),
),
),
),
);
print json_encode($var);
prints out:
{
"mydata": {
"name": "Name",
"type": "default",
"date": [
{
"s1": 1485,
"name": "1485",
"child": {
"credit": "",
"caption": ""
}
}
]
}
}
No need to try and add stdClass instances or anything like that in PHP. Just build out a nice clean array and JSON encode will convert to object properties and arrays where necessary.

How to create a JSON object

I am trying to create an JSON object out of a PHP array. The array looks like this:
$post_data = array('item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts);
The code to encode the JSON look like this:
$post_data = json_encode($post_data);
The JSON file is supposed to look like this in the end:
{
"item": {
"is_public_for_contacts": false,
"string_extra": "100000583627394",
"string_value": "value",
"string_key": "key",
"is_public": true,
"item_type_id": 4,
"numeric_extra": 0
}
}
How can I encapsulate the created JSON code in the "item": { JSON CODE HERE }.
Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}", you better make sure to force json_encode() to encode as object, by passing the JSON_FORCE_OBJECT constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification.
Although the other answers posted here work, I find the following approach more natural:
$obj = (object) [
'aString' => 'some string',
'anArray' => [ 1, 2, 3 ]
];
echo json_encode($obj);
You just need another layer in your php array:
$post_data = array(
'item' => array(
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
)
);
echo json_encode($post_data);
You could json encode a generic object.
$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);
$post_data = [
"item" => [
'item_type_id' => $item_type,
'string_key' => $string_key,
'string_value' => $string_value,
'string_extra' => $string_extra,
'is_public' => $public,
'is_public_for_contacts' => $public_contacts
]
];
$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;

Categories