count JSON multidimendional array in php - php

i got this json format form form-builder plugin, in hope someone could help out i need to count the number of times certain fields occur so i can create a database for them
[ { "cssClass" : "checkbox",
"required" : "false",
"title" : "hello save",
"values" : { "2" : { "baseline" : "false",
"value" : "save"
},
"3" : { "baseline" : "false",
"value" : " save 2"
},
"4" : { "baseline" : "false",
"value" : "save 3"
},
"5" : { "baseline" : "false",
"value" : "save 4"
},
"6" : { "baseline" : "false",
"value" : "save 5 "
},
"7" : { "baseline" : "false",
"value" : "Save 6"
}
}
},
{ "cssClass" : "textarea",
"required" : "false",
"values" : "you did not say hello properly"
},
{ "cssClass" : "checkbox",
"required" : "false",
"title" : "whats up save",
"values" : { "2" : { "baseline" : "false",
"value" : "i got your back"
},
"3" : { "baseline" : "false",
"value" : "i got your back 2"
},
"4" : { "baseline" : "false",
"value" : "i got your back 3"
},
"5" : { "baseline" : "false",
"value" : "1 got your back 4"
},
"6" : { "baseline" : "false",
"value" : "i got your back 5"
}
}
}
]
i want to be able to count the number of cssClass checkbox and the corresponding values value to help create a database table for insert in mysql or mongodb
i will like it in a format like this
count($data[cssclass])
count($data[cssClass][values])
i get
Notice: Undefined index: cssClass in C:\wamp\www\callme\repo\index.php on line 45
i will appreciate any solution in php or nodejs sice am quite new to Json
!============================================================================!
Hello guys, thanks for your timely response, i appreciate and feel very privileged to have u guy but it didn't really solve the challenge maybe i was not clear enough so this is the program logic. for the given json data i will like to sort it in a way that i can get the tile of the checkbox and its values which to create database entries for the user e.g
for array with checkbox get title and number of values (value) so i can have something like say
checkbox1 title values = 6
checkbox2 title values = 5

The JSON Object in your example is an Array. You can either use the following code to count all of the values:
$total = 0;
foreach($data as $row){
$total += count($row['values']);
}
or you can use the following to reach one object:
count($data[0]['values']);
Of course you'll need to use
json_decode($json_string,true)
to convert your json object into a PHP array.

You never deal with "json objects" directly. JSON is just a text string that happens to represent a javascript-style data structure. You always deal with NATIVE data structures, so
$array = json_decode($your_json);
$count = count($array['cssclass']);
Is what you'd do in PHP - convert to a native PHP array/object, then do your counting on that.
And as for what you should be counting on, once you've decoded back to native PHP, you can examine the actual structure with
var_dump($array);

This should get you there:
<?php
$json = '[{"cssClass":"checkbox","required":"false","title":"hello save","values":{"2":{"value":"save","baseline":"false"},"3":{"value":" save 2","baseline":"false"},"4":{"value":"save 3","baseline":"false"},"5":{"value":"save 4","baseline":"false"},"6":{"value":"save 5 ","baseline":"false"},"7":{"value":"Save 6","baseline":"false"}}},{"cssClass":"textarea","required":"false","values":"you did not say hello properly"},{"cssClass":"checkbox","required":"false","title":"whats up save","values":{"2":{"value":"i got your back","baseline":"false"},"3":{"value":"i got your back 2","baseline":"false"},"4":{"value":"i got your back 3","baseline":"false"},"5":{"value":"1 got your back 4","baseline":"false"},"6":{"value":"i got your back 5","baseline":"false"}}}]';
$obj = json_decode($json, true);
$cssClasses = array_filter($obj, function($el){ return $el["cssClass"] == "checkbox" });
print_r($cssClasses);

I think with a loop you will get out what you want (but I am not 100% sure if I understand you correctly).
<?php
$json = '[ { "cssClass" : "checkbox", "required" : "false", "title" : "hello save", "values" : { "2" : { "baseline" : "false", "value" : "save" }, "3" : { "baseline" : "false", "value" : " save 2" }, "4" : { "baseline" : "false", "value" : "save 3" }, "5" : { "baseline" : "false", "value" : "save 4" }, "6" : { "baseline" : "false", "value" : "save 5 " }, "7" : { "baseline" : "false", "value" : "Save 6" } } }, { "cssClass" : "textarea", "required" : "false", "values" : "you did not say hello properly" }, { "cssClass" : "checkbox", "required" : "false", "title" : "whats up save", "values" : { "2" : { "baseline" : "false", "value" : "i got your back" }, "3" : { "baseline" : "false", "value" : "i got your back 2" }, "4" : { "baseline" : "false", "value" : "i got your back 3" }, "5" : { "baseline" : "false", "value" : "1 got your back 4" }, "6" : { "baseline" : "false", "value" : "i got your back 5" } } } ]';
// first convert the json string to an array (as the others already said)
$array = json_decode($json);
$boxes = array();
foreach ($array as $obj)
{
if ($obj->cssClass == "checkbox")
{
$boxes[] = array(
"title" => $obj->title,
"count_values" => count( (array)$obj->values ) // cast the object as an array to count the indexes
);
}
}
?>
This will give you a new array, containing only the checkboxes with titles and the number of values.
/*
Array
(
[0] => Array
(
[title] => hello save
[count_values] => 6
)
[1] => Array
(
[title] => whats up save
[count_values] => 5
)
)
*/

Related

Create a desired JSON format using data stored in PHP

So I have a bunch of arrays inside which I have all the data I require to pass to a third party app. Problem is that they need it in a specific JSON format, and I do not have an idea how I can do that. The data format they require is like:
{
"appData" : {
"appKey" : "blah blah",
"synth" : {
"synth1" : {
"mono" : [
{
"monoId" : "529",
"templates" : [
{
"monoSequenceMap" : [
{
"map" : {
"X" : "3",
"Y" : "1"
},
"position" : {
"scale" : "1",
"x1" : "100",
"x2" : "150",
"y1" : "2000",
"y2" : "2500"
}
},
{
"map" : {
"X" : "2",
"Y" : "4"
},
"position" : {
"scale" : "1",
"x1" : "200",
"x2" : "550",
"y1" : "1000",
"y2" : "1500"
}
},
{
"map" : {
"X" : "3",
"Y" : "3"
},
"position" : {
"scale" : "1.5",
"x1" : "300",
"x2" : "750",
"y1" : "1750",
"y2" : "1800"
}
},
{
"map" : {
"X" : "4",
"Y" : "1"
},
"position" : {
"scale" : "1.5",
"x1" : "680",
"x2" : "790",
"y1" : "1950",
"y2" : "1850"
}
}
],
"templateId" : "01_A_19"
}
]
}
],
"synthId" : "XXXXXXXXXX"
}
}
}
}
I just want some pointers on how to convert the data I have into this JSON string. I think I need to use json_encode. Should I create a new class called 'appData' class then create each object/array inside it? or should I just write a string in this format into a text file?
My problem is that I cannot wrap my head around having all these objects inside objects thing...like for e.g, in the JSON synth is an object which contains synth1, synth2 etc which will be objects which in turn will have mono which will be an array of objects...And I am not sure how to tackle that..
Any pointers is greatly appreciated!
Are your arrays multidimensional? Like:
$array = array(
"data_table_1" => array(
"item1" => "Item 1",
"item2" => "Item 2"
),
"data_table_1" => array(
"item1" => "Item 1",
"item2" => "Item 2"
)
);
If so, all you have to use is use json_encode and that will do all the encoding for you:
$json = #json_encode($array);
==== Edit ====
arrays do not have to be multidimensional. Even an array with a single key => value will work. Just be sure you have keys for values, so they're registered correctly.

How to extract a value from this JSON response

I am using the file_get_contents() function in PHP to retrieve the contents on a page containing a JSON response. However, I am struggling to get the "text" data.
$response = file_get_contents(someData)
I can use var_dump(json_decode($response)); to show the data, however, I am trying to get the data from the "text" field only within duration.
So far I have tried
$response[0];
$response->rows[0]->elements[0]->duration[0]->text;
But I cannot seem to get the data. I have pasted the response below
{
"destination_addresses" : [ "Manchester, UK", "Liverpool, Merseyside, UK" ],
"origin_addresses" : [ "London, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "335 km",
"value" : 335444
},
"duration" : {
"text" : "3 hours 36 mins",
"value" : 12955
},
"status" : "OK"
},
{
"distance" : {
"text" : "354 km",
"value" : 354415
},
"duration" : {
"text" : "3 hours 43 mins",
"value" : 13387
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
$response = json_decode(file_get_contents(someData));
$text = $response->rows[0]->elements[0]->duration->text;
var_dump($text);
Your only mistake was a [0] after duration.

How to merge two JSON files into one

I have two json files named: users.json and users_custom.json which I created from mysql database using php. users.json file looks like:
[{
"user_id" : "1",
"Name" : "Mr. A",
"phone" : "12345"
},
{
"user_id" : "2",
"Name" : "Mr. B",
"phone" : "23456"
}]
and users_custom.json file looks like:
[{
"user_id" : "1",
"Name" : "Mr. A Modified",
"email" : "someone#gmail.com"
},
{
"user_id" : "2",
"Name" : "Mr. B",
"address" : "some address"
}]
so, in users_custom.json file I have modified some fields and also added some new fields. Now, I want to merge users_custom.json over users.json file into users_final.json file. At the end users_final file should looks like this:
[{
"user_id" : "1",
"Name" : "Mr. A Modified",
"phone" : "12345"
"email" : "someone#gmail.com"
},
{
"user_id" : "2",
"Name" : "Mr. B",
"phone" : "23456"
"address" : "some address"
}]
At the end I will import the users_final.json file to MongoDB database. Any idea or example code will be greatly appreciated. Thanks in advance.
This should be fairly straightforward, get contents of both files, decode them both, loop them accordingly, if the user id's match, merge them, after that process is complete, encode the resultant, then write the file. Example:
// $contents_of_users = file_get_contents('users.json');
$contents_of_users = '[{ "user_id" : "1", "Name" : "Mr. A", "phone" : "12345"},{ "user_id" : "2", "Name" : "Mr. B", "phone" : "23456"}]';
// $contents_of_users_custom = file_get_contents('users_custom.json');
$contents_of_users_custom = '[{ "user_id" : "1", "Name" : "Mr. A Modified", "email" : "someone#gmail.com"},{ "user_id" : "2", "Name" : "Mr. B", "address" : "some address"}]';
$data_user = json_decode($contents_of_users, true);
$data_user_custom = json_decode($contents_of_users_custom, true);
$final = $data_user;
foreach($final as $key => &$user) {
foreach($data_user_custom as $user_custom) {
if($user['user_id'] == $user_custom['user_id']) {
$user = array_merge($user, $user_custom);
}
}
}
$final = json_encode($final, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($final);
file_put_contents('users_final.json', $final);
Sample Output

Retrieve elements using $slice

My result is following after executing find() query.
{
"_id" : ObjectId("5384928a03ea2e75268b4567"),
"0" : {
"name" : "mango",
"quantity" : "10"
},
"1" : {
"name" : "apple",
"quantity" : "14"
},
"2" : {
"name" : "banana",
"quantity" : "11"
},
"3" : {
"name" : "grapes",
"quantity" : "19"
},
"4" : {
"name" : "lichi",
"quantity" : "13"
},
"5" : {
"name" : "orange",
"quantity" : "10"
},
"6" : {
"name" : "lemon",
"quantity" : "10"
},
"7" : {
"name" : "pear",
"quantity" : "10"
},
"8" : {
"name" : "cherry",
"quantity" : "10"
},
"9" : {
"name" : "kiwi",
"quantity" : "10"
}
}
Now i want only any five elements in result(like from 2nd element to 6th element).
How to do this using $slice or is there any other method to retrieve only five elements in result?
The important thing here is, do you actually have an array for $slice to work on? There seems to be a bit of a misconception here common to people working with PHP as the way that language typically represents an array.
The mongo shell ( for example ) will show the clear distinction, where an array actually looks like this in it's JSON representation:
{
"_id" : ObjectId("5384928a03ea2e75268b4567"),
"arrayField": [
{
"name" : "mango",
"quantity" : "10"
},
{
"name" : "apple",
"quantity" : "14"
},
{
"name" : "banana",
"quantity" : "11"
},
{
"name" : "grapes",
"quantity" : "19"
}
]
}
That structure can use the $slice operator to return the elements you want. As an example here, 2 documents from index position 1
db.collection.find({},{ "arrayField": { "$slice": [ 1,2] }})
{
"_id" : ObjectId("5384928a03ea2e75268b4567"),
"arrayField" : [
{ "name" : "apple", "quantity" : "14" },
{ "name" : "banana", "quantity" : "11" }
]
}
The structure you are showing is just a bunch of key names for sub-documents within the top level document. It is probably a mistake but you just specify those fields in the projection. It's not an array so $slice does not apply:
db.collection.find({}, { "1": 1, "2": 1, "3": 1, "4": 1, "5": 1, "6": 1 })
But that probably is not what you want, so it looks like you will need to fix your data so it is an array.
$slice is used to control the number of elements in an array returned by the query, but I don't see an explicit array in your results. Your document should look something like:
{
"_id" : ObjectId("5384928a03ea2e75268b4567"),
"fruit" : [
{
"name" : "mango",
"quantity" : "10"
},
{
"name" : "apple",
"quantity" : "14"
}
]
}
Then you could query it with something like:
db.collection.find({},{"fruit": {$slice:[1:6]}})
If you want to get only 5 record from document you can use limit(), if you want to skip few of the record then use skip().
For Example :
db.collection.find().skip(2).limit(5);
This query fetch 5 documents after first 2 documents.

How to create this type of JSON data from PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to create a json object as follows from php. How could I do it. I'm using MySQL table to get data.
{
"JSChart" : {
"datasets" : [
{
"type" : "line",
"id" : "blue",
"data" : [
{
"unit" : "1",
"value" : "80"
},
{
"unit" : "2",
"value" : "40"
},
{
"unit" : "3",
"value" : "60"
},
{
"unit" : "4",
"value" : "65"
},
{
"unit" : "5",
"value" : "50"
},
{
"unit" : "6",
"value" : "50"
},
{
"unit" : "7",
"value" : "60"
},
{
"unit" : "8",
"value" : "80"
},
{
"unit" : "9",
"value" : "150"
},
{
"unit" : "10",
"value" : "100"
}
]
},
{
"type" : "line",
"id" : "green",
"data" : [
{
"unit" : "1",
"value" : "100"
},
{
"unit" : "2",
"value" : "55"
},
{
"unit" : "3",
"value" : "80"
},
{
"unit" : "4",
"value" : "115"
},
{
"unit" : "5",
"value" : "80"
},
{
"unit" : "6",
"value" : "70"
},
{
"unit" : "7",
"value" : "30"
},
{
"unit" : "8",
"value" : "130"
},
{
"unit" : "9",
"value" : "160"
},
{
"unit" : "10",
"value" : "170"
}
]
},
{
"type" : "line",
"id" : "gray",
"data" : [
{
"unit" : "1",
"value" : "150"
},
{
"unit" : "2",
"value" : "25"
},
{
"unit" : "3",
"value" : "100"
},
{
"unit" : "4",
"value" : "80"
},
{
"unit" : "5",
"value" : "20"
},
{
"unit" : "6",
"value" : "65"
},
{
"unit" : "7",
"value" : "0"
},
{
"unit" : "8",
"value" : "155"
},
{
"unit" : "9",
"value" : "190"
},
{
"unit" : "10",
"value" : "200"
}
]
}
],
"optionset" : [
{
"set" : "setSize",
"value" : "550, 300"
},
{
"set" : "setAxisValuesNumberY",
"value" : "5"
},
{
"set" : "setIntervalStartY",
"value" : "0"
},
{
"set" : "setIntervalEndY",
"value" : "200"
},
{
"set" : "setLabelX",
"value" : "[2,'p1']"
},
{
"set" : "setLabelX",
"value" : "[4,'p2']"
},
{
"set" : "setLabelX",
"value" : "[6,'p3']"
},
{
"set" : "setLabelX",
"value" : "[8,'p4']"
},
{
"set" : "setLabelX",
"value" : "[10,'p5']"
},
{
"set" : "setAxisValuesNumberX",
"value" : "5"
},
{
"set" : "setShowXValues",
"value" : "false"
},
{
"set" : "setTitleColor",
"value" : "'#454545'"
},
{
"set" : "setAxisValuesColor",
"value" : "'#454545'"
},
{
"set" : "setLineColor",
"value" : "'#A4D314', 'green'"
},
{
"set" : "setLineColor",
"value" : "'#BBBBBB', 'gray'"
},
{
"set" : "setTooltip",
"value" : "[1,' ']"
},
{
"set" : "setTooltip",
"value" : "[2,' ']"
},
{
"set" : "setTooltip",
"value" : "[3,' ']"
},
{
"set" : "setTooltip",
"value" : "[4,' ']"
},
{
"set" : "setTooltip",
"value" : "[5,' ']"
},
{
"set" : "setTooltip",
"value" : "[6,' ']"
},
{
"set" : "setTooltip",
"value" : "[7,' ']"
},
{
"set" : "setTooltip",
"value" : "[8,' ']"
},
{
"set" : "setTooltip",
"value" : "[9,' ']"
},
{
"set" : "setTooltip",
"value" : "[10,' ']"
},
{
"set" : "setFlagColor",
"value" : "'#9D16FC'"
},
{
"set" : "setFlagRadius",
"value" : "4"
},
{
"set" : "setAxisPaddingRight",
"value" : "100"
},
{
"set" : "setLegendShow",
"value" : "true"
},
{
"set" : "setLegendPosition",
"value" : "490, 80"
},
{
"set" : "setLegendForLine",
"value" : "'blue', 'Click me'"
},
{
"set" : "setLegendForLine",
"value" : "'green', 'Click me'"
},
{
"set" : "setLegendForLine",
"value" : "'gray', 'Click me'"
}
]
}
}
Can any one help me to do that. If there any tutorials to follow. I want to use JSChart to plot data on my HTML.
Your way is to use json_encode function:
return json_encode(array('JSChart' => array(
'datasets' => array(
...
),
));
You should try something like below code to populate your json with PHP and MySQL:
$info=array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){
array_push($info,$row);
}
echo json_encode($info);
would return:
array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } [1]=> array(3) { ["id"]=> string(1) "2" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } }
json:
[{"id":"1","firstname":"foo","lastname":"bar"},{"id":"2","firstname":"foo","lastname":"bar"}]

Categories