Repetitive Data in JSON file - php

I want to repeat the unit and pcs sections in the JSON file.
For example:
$rows[] = array(
'unit' => 'Example',
'pcs' =>
array('1 for Example', '2 for Example'),
);
Result:
[
{"unit":"Example","pcs":["1 for Example","2 for Example"]}
]
How to do this type of JSON?
Target:
[
{"unit":"Example",
"pcs":
["1 for Example","2 for Example"]},
{"unit":"ExampleSecond",
"pcs":
["1 for ExampleSecond","2 for ExampleSecond"]}
]

Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]

Related

Laravel How can I return array of objects

I've got simple array of objects:
"myObject" => [
'key1' => ["property1" => 'value1', "property2" => 'value2'],
'key2' => ["property1" => 'value1', "property2" => 'value2'],
...
],
When I'm returning this via laravel dot syntax:
return [
'listOfObjects' => trans(objects)
]
I've got:
myObject: {
key1: {property1:'value1', property2:'value2'},
key2: {property1:'value1', property2:'value2'},
etc..
}
It's simple.
Now how can I modify my return to get only an array of objects, without numbers:
myObject: {
{property1:'value1', property2:'value2'},
{property1:'value1', property2:'value2'},
etc..
}
Any ideas?
I don't think it is possible to solve in PHP. As it is said in the manual
"...index may be of type string or integer. When index is omitted, an
integer index is automatically generated, starting at 0..."
Also, what you are asking seems to be quite pointless. If you could describe what it is you are trying to accomplish, people might be able to help you better.
The function to use in this case is:
$tryit = trans('objects');
$new = collect($tryit)->flatten(1);
$new->values()->all();
unfortunatelly there is a bug in Laravel 5.6 on this function and it digs two level deep instead of one :/
[edit]
I think I now understand what you want. What you call an Array in PHP is not necessarily an Array in JSON. For JSON your "myObject" is an Object.
For JSON to recognize something as an Array, it can only have numbers as keys.
So change the keys from "key1", "key2", ... into 0, 1, ...
$result = [];
foreach($myObject as $element){
$result[] = $element;
}
return $result;
After that, $result looks like this
$result = [
0 => ["prop1" => "val1", "prop2" => "val2"],
1 => ["prop1" => "val1", "prop2" => "val2"]
]
Or equivalently in the short notation
$result = [
["prop1" => "val1", "prop2" => "val2"],
["prop1" => "val1", "prop2" => "val2"]
]
Now JSON should recognize this as an Array instead of an Object when Laravel converts $result to JSON or you make it yourself: return response()->json($result);
[previous:]
You can not return an object which has values but no keys.
The simplest form of keys are numbers, which is what arrays are using.

json_encode( json_encode (array) )

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format
var arr = [
[45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}],
etc.
];
My script is along the lines of
while ...
array_push(
$arrBubble,
array(
11,
123,
1236,
json_encode(
array('label' => $car, 'color' => 'skyblue')
)
);
}
echo json_encode($arrBubble);
The problem is that the result is
[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]
The double json_encode has encoded the object(?) as a literal string.
What's the best way to work around this?
There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.
var_dump(json_encode([
11,
123,
1236,
['label' => $car, 'color' => 'skyblue']
]));
Outputs the structure you want:
string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"

make object from two arrays with the seperate arrays as properties

I have a PHP function that give me two seperate JSON arrays (array1 and array2). How can I merge them in an object with properties, like this:
{
"array1": [ {"type": "column", "valueField": ..., "descriptionField": ..., }]
"array2": [ {"type": "column", "valueField": ..., "descriptionField": ..., }]
}
Thanks in advance
This is just a simple example of how you can do it, you can improve it however you like, depending what kind of situation you need it for.
// Initialising arrays
$array1 = ['type' => 'column', 'valueField' => '.1.', 'descriptionField' => '.11.'];
$array2 = ['type' => 'column', 'valueField' => '.2.', 'descriptionField' => '.22.'];
// Turn them manually into jsons
$obj1 = json_encode($array1);
$obj2 = json_encode($array2);
// Merge the two jsonified arrays in a single array with whichever keys you prefer
$mix = ['array1' => $obj1, 'array2' => $obj2];
// Turn the merged "mix" array into json
$mix = json_encode($mix);
// Check the output
printf($mix);
/* Prints out:
{
"array1":"{"type":"column", "valueField":".1.", "descriptionField":".11."}",
"array2":"{"type":"column", "valueField":".2.", "descriptionField":".22."}"
}
*/
You can fiddle around with it in in this SANDBOX, have some fun with it.

php json_encode received at jquery end, lost order?

when i return a key pair array in php to ajax call at jquery (javascript) end the order i have maintain in php get lost. how to preserve array order.
e.g array('node' => 'abc', 'test' => 'xyz', 'a' => 'xyz') this array disorder to array('a' => 'xyz', 'node' => 'abc', 'test' => 'xyz') in jquery. Any help.
JavaScript has no concept of an associative array as in PHP, so when you JSON encode something, it becomes an object instead. The ordering of object keys isn't important, so relying on them could lead to unexpected behaviour.
If ordering is important, you should consider using a non-associative array with objects (or associative arrays) as values.
$myArray = array(
array('x' => 'node', 'y' => 'abc'),
array('x' => 'test', 'y' => 'xyz'),
array('x' => 'a', 'y' => 'xyz'),
);
That would encode as:
[
{"x": "node", "y": "abc"},
{"x": "test", "y": "xyz"},
{"x": "a", "y": "xyz"}
]

Help trying to generate tricky multidimensional array format

I'm having trouble trying to build an array in PHP which will output in the JSON format I am looking for. I will show you what I am trying to achieve and where I have got to so far:
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
I am looping through db results and trying to build arrays to output the above json, my php looks like this (which is obviously not right yet):
//build the data
$data = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
$illnesses[] = $data;
This code outputs the following json:
[
{
[
[{"x":2,"y":6},{"x":2,"y":6}],
[{"x":2,"y":6},{"x":5,"y":6}],
[{"x":4,"y":6},{"x":4,"y":6}]
]
}
]
Any pointers on this would be great!
Basically, if you know your desired JSON output already, you can simply json_decode it to get it's representation in PHP. The var_export function prints the structure in parseable format. You can also use print_r or var_dump to dump the structure though.
$json = <<< JSON
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
JSON;
var_export( json_decode($json) );
The above approach is universal. Just decode and dump the structure. Then assemble your code to create this structure and encode.
do this:
$data['data'] = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
Looking at the JSON string, you can see that:
it is an array (it is surrounded by [ and ])
each element is an object (surrounded by { and })
the objects have an element data that is itself an array
that array consists of two objects with an x and a y property
It is important to know that a JSON object is represented in PHP by an associative array (when json_encode()'ing, json_decode() has a specific parameter to use either a stdClass or an assoc. array).
So the php structure looks like this:
$data = array(
array('data' => array(array('x' => 3, 'y' => 0), array('x' => 10, 'y' => 0))
,array('data' => array(array('x' => 11, 'y' => 0), array('x' => 13, 'y' => 0))
,array('data' => array(array('x' => 12, 'y' => 1), array('x' => 17, 'y' => 1))
);

Categories