Generate a jstree using json response zend php - php

In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails->toArray();
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
When printing the jsonResonse (print_r($jsonResponse)). I'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
how to generate a jstree using json response
By jstree demo i written a code like this for getting tree structure but i am unable to get a tree.
Please help me
jQuery(document).ready(function(){
//alert("get tree view");
jQuery("#treeView").jstree({
// This example uses JSON as it is most common
"json_data" : {
// This tree is ajax enabled - as this is most common, and maybe a bit more complex
// All the options are almost the same as jQuery's AJAX (read the docs)
"ajax" : {
// the URL to fetch the data
"url" : "groupDetails.php",
// the `data` function is executed in the instance's scope
// the parameter is the node being loaded
// (may be -1, 0, or undefined when loading the root nodes)
"data" : function (n) {
// the result is fed to the AJAX request `data` option
return {
"operation" : "get_children",
"id" : n.attr ? n.attr("id").replace("node_","") : 1
};
}
}
},
"ui" : {
"select_limit" : 1
},
"themes" : {
"theme" : "default",
"dots" : true,
"icons" : true
},
"types" : {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth" : -2,
"max_children" : -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children" : [ "drive" ],
"types" : {
// The default type
"default" : {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children" : "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon" : {
"image" : "./file.png"
}
},
// The `folder` type
"folder" : {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./folder.png"
}
},
// The `drive` nodes
"drive" : {
// can have files and folders inside, but NOT other `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./root.png"
},
// those prevent the functions with the same name to be used on `drive` nodes
// internally the `before` event is used
"start_drag" : false,
"move_node" : false,
"delete_node" : false,
"remove" : false
}
}
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu" ]
})
});

Your json should look like this:
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]
You can put anything you want at the "attr" hash, basically it can hold other information you might need.

Related

Removing an element from an array which is an element of an object

I'm working on a filter system to filter out food items being displayed on a menu. Every document in the menu collection contains the name of the category (or course if you will) and an array of food items.
I've tried various solutions such as the following code which gets me closer to the desired output.
foreach($menu as $category){
foreach($category["fooditems"] as $fooditem){
if ($fooditem["vegetarian"] == false){
if (($key = array_search($fooditem, (array) $category["fooditems"])) !== false)
unset($category["fooditems"][$key]);
}
}
}
Before:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
},
{
"name" : "Horse Meat",
"vegetarian" : false,
},
{
"name" : "Some more meat",
"vegetarian" : false,
}
]
}
Expected after:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
}
]
}
Actual after:
{
"category" : "Starters",
"fooditems" : [
{
"name" : "No meat",
"vegetarian" : true,
},
{
"name" : "Some more meat",
"vegetarian" : false,
}
]
}
The problem is after it spots a non-vegetarian food item and unsets it, it stops looping. I have no idea why this occurs.
Thank you to anyone who answers :)
After decoding the JSON to an array with true you can filter and return only what is equal to true:
$menu['fooditems'] = array_filter($menu['fooditems'],
function($v) {
return $v['vegetarian'] === true;
});
To use your loop, just track the key and unset using the full path to the array:
foreach($menu['fooditems'] as $key => $values) {
if($values['vegetarian'] === false) {
unset($menu['fooditems'][$key]);
}
}

Parse json with PHP. Getting Undefined property: stdClass errors

I am having some issues parsing a json file from Jenkins using PHP
{
"actions" : [
{
"causes" : [
{
"shortDescription" : "Started by an SCM change"
}
]
},
{
},
{
},
{
"buildsByBranchName" : {
"origin/release_5.6.0" : {
"buildNumber" : 242,
"buildResult" : null,
"marked" : {
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"branch" : [
{
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"name" : "origin/release_5.6.0"
}
]
},
"revision" : {
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"branch" : [
{
"SHA1" : "fde4cfd86b8511d328037b9e9c55876007bb6e67",
"name" : "origin/release_5.6.0"
}
]
}
},
"origin/release_5.7.0" : {
"buildNumber" : 315,
"buildResult" : null,
"marked" : {
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"branch" : [
{
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"name" : "origin/release_5.7.0"
}
]
},
"revision" : {
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"branch" : [
{
"SHA1" : "ae2cbf69a25e0632e0f1d3eeb27a907b154efce0",
"name" : "origin/release_5.7.0"
}
]
}
},
I have tried doing the following
//Read in JSON object
$json_file2 = file_get_contents('url.com/json');
//Decode JSON file
$test = json_decode($json_file2); //object
//print_r($json_file2);
echo $test->causes;
I am also trying to access the different sections in "buildsByBranchName". I have tried many different variations of the code above, but I keep getting "Undefined property: stdClass" errors.
You are not accessing that value properly. causes resides under actions which is an array. Your code also won't work because causes is an array.
// This is an array so you can't use echo here.
$causes = $test->actions[0]->causes;
// echo out the shortDescription
echo $causes[0]->shortDescription;
or
echo $test->actions[0]->causes[0]->shortDescription;

ammaps / amcharts using dataLoader and passing post

Using ammaps' dataLoader, is there a way to pass post parameters to an external file?
I'm creating a report that contains a map, which when clicked, will provide a list of news articles from a MySQL table. I'm pulling in json data using dataLoader. However, I need to be able to pass a value (reportId) to the script that generates the json file.
here's my code:
var map = AmCharts.makeChart("mapdiv", {
type: "map",
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false//,
// tried this:
//"type" : "post",
//"data" : {"reportIdFromPost" : 1}
},
. . . //the rest of the map config
And this is maparticlesfeed.json.php:
<?php include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$POST['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"_comment" : "Here, instead of hard-coding the headlines, we will iterate through $articlesList",
"areas" : [
{ "title" : "Virginia",
"id" : "US-VA",
"selectable" : true,
"numArticles" : 4,
"articles" : [
{ "headline" : "This is the first headline",
"link" : "link url"
},
{ "headline" : "This is the second headline",
"link" : "link url"
},
{ "headline" : "This is the third headline",
"link" : "link url"
},
{ "headline" : "This is the fourth headline",
"link" : "link url"
}
]
},
{ "title" : "Tennessee",
"id" : "US-TN",
"selectable" : false,
"numArticles" : 6
}
]
}
I went the jQuery route to solve this. I'd still like to know if there's a way to do this with dataLoader, but here's a workaround in case anyone else has this issue in the future:
$.ajax({
dataType: "json",
url: "maparticlesfeed.json.php",
data: { reportIdFromPost: 1 },
type: "post",
success: function(data){
console.log(data); // for debugging
makeMap(data);
},
error: function(data) {
console.log('it did not work.');
console.log(data.responseText);
}
});
function makeMap(theData) {
var map = AmCharts.makeChart("mapdiv", {
type: "map",
/* DON'T NEED THIS ANYMORE:
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false
},*/
// replace instead with this:
"dataProvider" : theData,
// ... the rest of the map config ...
}
});
And, in maparticlesfeed.json.php:
<?php
include('database-connect.php');
$con=Database::connect();
if(!empty($_POST) && isset($_POST['reportIdFromPost']) ) {
$postedReportId= $_POST['reportIdFromPost'];
}
include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedReportId ");
$query->execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"areas" : [
// Code to json_encode the results from $articlesList
]
}
It may be that you're posting json data and then not decoding it when you're trying to use the value in your php script.
Try this at the top of maparticlesfeed.json.php:
<?php
include('database-connect.php');
$postedValues = json_decode($POST['reportIdFromPost'], true);
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedValues['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
You'll also need to uncomment the two lines in the map config:
"type" : "post",
"data" : {"reportIdFromPost" : 1}
Maybe you could add the parameters in the "url" parameter of the dataloader.
"url": "urlA.do?param1=" + $('.selector').val()
and then in some trigger (ie. button click) modify the url and reload
var url = "same URL with different parameters values";
chart.dataLoader.url = url;
chart.dataLoader.loadData()

Find a document with Doctrine ODM with equals condition on nested array of objects

I got this kind of document:
{
"_id" : ObjectId("54ad5c3b9a703a3c088b4567"),
"hard" : 750,
"coordinates" : {
"x" : 0.2388169910939489,
"y" : 0.7996551291084174
},
"indicator" : 500,
"networkIdList" : {
"networkIdData" : [
{
"networkId" : "abc123",
"type" : "SomeNetwork"
},
{
"networkId" : "123asdf",
"type" : "AnotherNetWork"
},
{
"networkId" : "abc123",
"type" : "OneMoreNetwork"
}
]
}
}
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork".
I have tried With this instruction:
$this->documentManager->createQueryBuilder('Mydocument') ->field('networkIdList.networkIdData.$.networkGamingId')->equals('abc123') ->field('networkIdList.networkIdData.$.type')->equals('')
->getQuery()
->execute());
But the cursor return no data.
I also try with
->where("function() {return this.networkIdList.networkIdData.$.networkGamingId == 'abc123'}")
but in this case i got an error that says the Object $ has no propierties.
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork"
$qb = $dm->createQueryBuilder('Foo')
->field('networkIdList.networkIdData.networkId')->equals('abc123')
->field('networkIdList.networkIdData.type')->equals('SomeNetwork');

How to get list of fields from Object in mongoDB?

I'm new in mongoDB, I saw enough examples but most show how to work with collections.
I have followed data stored in mongoDB under DB name myDB:
"_id" : "some_table_name",
"content" : [{
"id" : "1",
"loctype" : "Clinic/Hospital",
"locname" : "KKH"
}, {
"id" : "2",
"loctype" : "Clinic/Hospital",
"locname" : "Singapore National Eye Centre"
}
}]
}
As you can see the model contains _id and content, where content is list of objects:
... ,
{
"id" : "ZZZ",
"loctype" : "ZZZ",
"locname" : "ZZZ"
},
...
PHP
$m = new MongoClient(/* ... */);
$db = $m->myDB;
$collection = $db->coll;
How can I fetch in PHP list of ids? a.e [1,2] in my case.
For sure I can get all model and extract ids but I try to do it stright from mongoDB.
Thanks.
It depends on how you want this formatted but here is a aggregation version which formats it in a nice way:
$mongo->collection->aggregate(array(
array('$unwind'=>'$content'),
array('$project'=>array('_id'=>'$content.id'))
))
It will print documents like:
[
{_id:1},
{_id:2}
]
Another way could be to just project the single field out with $db->collection->find(array(),array('content.id'=>1))
I should note though, it would most likely to better to just do this in PHP. Through PHP is the only way you can get the exact output you are seeking I believe.
Try this:
$collection = new MongoCollection($db, 'collection_name');
$query = array(
// Some restrictions can be here
);
$ids = array();
$cursor = $collection->find($query);
foreach ($cursor as $doc) {
$doc = (array) $doc;
$ids[] = $doc["id"];
}
var_dump($ids);
Use mapreduce followed by distinct, as follows:
mr = db.runCommand({
"mapreduce" : "things",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "things" + "_keys"
})
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
Or use Variety...

Categories