slack, php and json - Valid Markup for iterating app selections - php

I've been trying to create a slack app which takes the basic information of the name and sku of the product and places it within a select box that appears in slack. Unfortunately my code to populate the valid json is going wrong somewhere when i try to itterate using a loop.
Valid Json is here:
{
"text": "Great! You want to find something!",
"attachments": [
{
"text": "Please type what you want to find",
"fallback": "Sorry! Cant do that at the moment!",
"callback_id": "cg_selectproduct",
"color": "#3AA3E3",
"attachment_type": "default",
"actions": [
{
"name": "cg_choice",
"text": "Find Product",
"type": "select",
"options": [
{
"text": "option1",
"value": "option1"
},
{
"text": "option2",
"value": "option2"
},
{
"text": "option3",
"value": "option3"
}]
}
]
}
]
}
This works perfectly fine without the iteration. I have no issues if i tell the app to go here. It displays all options correctly.
Invalid PHP
$check = ($dbh->prepare("SELECT * FROM product_list WHERE FAMILY='PARENT'"));
$check->execute();
$row = $check->fetchAll();
// execute a pdo search to find all product parents
$jsonInput = "";
foreach($row as $rows){
$jsonInput .= '"text"=>"' . $rows['PRODUCT_NAME'] . '", "value" => "' . $rows['SKU'] . '",';
}
$jsonInput = rtrim($jsonInput, ',');
//Create an iterative string which will contain the product names and skus, removing the comma at the end.
header('Content-Type: application/json');
//Set the content type to json
$optionSelect = array(
"text" => "Great! You want to find something!",
"attachments" =>array(
"text" => "Please type what you want to find",
"fallback" => "Sorry! Cant do that at the moment!",
"callback_id" => "cg_selectproduct",
"color"=> "#3AA3E3",
"attachment_type" => "default",
"actions" => array(
"name" => "cg_choice",
"text" => "Find Product",
"type" => "select",
"options" => array($jsonInput)
)
)
);
//Create and itterate the options for the selection so it's populated
print_r(json_encode($optionSelect));
//print to show json
I'm not 100% sure where i'm going wrong with this. Maybe i'm thinking about a minor part a little too much. Can anyone here help me with where i'm going wrong?

$jsonInput = [];
foreach($row as $rows) {
$jsonInput[] = array(
'text' => $rows['PRODUCT_NAME'],
'value' => $rows['SKU']
);
}
// ...........
"options" => $jsonInput

Related

creating json output using php

I have this so far :
if (is_request_var('requestor') == 'PPA'){
$dataJson[][] = array("status" => "success","value" => $fetchValue ,"postcode" => $fetchPostCode,"params"=>"");
$notice = $dataJson;
}
I want to get (refer below) from PHP how do i arrange my PHP array code
jQuery191013316784294951245_1485527378760([
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e KENYATTA AVENUE, GENERAL POST OFFICE, 00100",
"postcode": "00100"
},
{
"value": "\u003cstrong\u003eNAIROBI\u003c/strong\u003e HAILE SALASSIE AVENUE, CITY SQUARE, QLD, 00200",
"postcode": "00200"
}
])
Try this:
$dataJson = array("value" => $fetchValue, "postcode" => $fetchPostCode);
$notice = json_encode($dataJson);
echo $notice;
Returns a string containing the JSON representation of value.
http://php.net/manual/en/function.json-encode.php

getting relational results from three tables into one nested array

i have googled for solution to my problem but nun helped me.
here i have three tables items, feeds and images. each item has one feed and one or more images.
i have 3 functions. one is to return records from items table the second one receives feeds_id (foreign key in items table) then return records from feeds table. the third function is to return all images related to items_id.
those functions are :
* To get all items in database:
function get_items(){
return $query = Database::getInstance('db')
->table('items')
->columns(
'id',
'items.rowid',
'items.feed_id as feed_id',
'title' )
->findAll();
}
* To get feed data from feeds table :
function get_feeds($id){
return $query = Database::getInstance('db')
->table('feeds')
->eq('id',$id)
->findAll();
}
* To get image data from images table :
function get_images($id){
return $query = Database::getInstance('db')
->table('images')
->columns('items_id','src as image_url',
'title as image_title',
'alt')
->eq('items_id',$id)
->findAll();
}
Then i have the following code to call those function and display the result in jsonformat:
$response['items'] = array();
$response['feeds'] = array();
$response['images'] = array();
foreach ($items = get_items() as $item) {
$response['items'][] = array(
'id' => (int)$item['rowid'],
'feed_id' => (int)$item['feed_id'],
'title' => $item['title'],
);
foreach ($feeds = get_feeds((int)$item['feed_id']) as $feed) {
$response['feeds'][] = array(
'title' => $feed['title'],
'logo_url' => $feed['logo_url'],
'site_url' => $feed['site_url'],
);
}
foreach ($images = get_images($item['id']) as $image) {
$response['images'][] = array(
'id' => $image['items_id'],
'url' => $image['image_url'],
'thumb' => $_SERVER['SERVER_NAME'] . /myServer/images/thumbs/'. 'thumb_'.basename($image['image_url']),
'title' => $image['image_title'],
'alt' => $image['alt']
);
}
}
echo json_encode($response, JSON_PRETTY_PRINT);
so, my expectation is to get json output like:
"items": [
{
"id": ,
"feed_id":
"title":
"feeds": [
{
"title": ,
"logo_url": ,
"site_url": "
}
]
"images": [
{
"id": ,
"url": ",
"thumb":
"title": "",
"alt": ""
},
{
....
}
]
}]
i mean each item array should include nested arrays of its related data coming from get_feeds and get_images functions.
instead of that, i get response like :
//here i select two items from my db
"items": [
{ //first_item
"id": ,
"feed_id":
"title":
},
{ //second_item
"id": ,
"feed_id":
"title":
}
],
"feeds": [
{ // feed data for first item
"title": ,
"logo_url": ,
"site_url": "
},
{ // feed data for second item
"title": ,
"logo_url": ,
"site_url": "
}
],
"images": [
{ // image data for first item
"id": ,
"url": ",
"thumb":
"title": "",
"alt": ""
},
{ // other images data
....
}
]
}]
as you see i am getting output without keeping relation between items, feeds and images, all of them are shown independently.
my queries are fine but i am suspecting error in my foreach statements.
i could fix this issue by joining those tree tables in one query, but i don't want to do that because i need to do validation and other operations to output comes from each table.
i appreciate your help
i found the solution. it is very easy :)
it is just like:
$response['items'][] = array(
'id' => (int)$item['rowid'],
'feed_id' => (int)$item['feed_id'],
'title' => $item['title'],
'feeds' => array(
)
'images' => array(
)
);

Build new custom Array from Wordpress $wpdb->get_results array

I'm currently taking the results of a table and using wp_send_json to using it as a JSON response. The data is encoded as expected, however I'd like to tweak the output a bit by changing the keys, formating, and order. I'm not sure how to rebuild the array and encode as json after so I'm looking for a little bit of help.
$stuff= $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_table"), ARRAY_A);
wp_send_json($stuff);
As of now the results I get via print_r look as follows.
Array(
[0] => Array(
[id] => 1[gender] => Male[email] => test#loas . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
) [1] => Array(
[id] => 2[gender] => Female[email] => femal#test . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
)
)
When encoded I get:
[{
"id": "1",
"gender": "Male",
"email": "test#loas.com",
"lat": "45",
"long": "-76",
"country_srt": "USA",
"country_long": "United States"
}, {
"id": "2",
"gender": "Female",
"email": "femal#test.com",
"lat": "98",
"long": "-34",
"country_srt": "USA",
"country_long": "United States"
}]
Thing is, I don't really need some of these values and also need to format some things to output for easy map plotting. For instance the country longform and gender go into an html formatted string. What I'm looking to do is transform this array to result in:
[ idhere: {
"value": "1",
"latitude": "45",
"longitude": "-76",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}, idhere: {
"value": "2",
"latitude": "98",
"longitude": "-34",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}]
I think what you need to do is break down the process down into steps (so you can change the data around) instead of sending your sql data to json directly.
build your own array
iterate over your sql result set while adding your own markup
send the output to json
something like:
$preJSON = array();
// select only columns you need
$sql = "SELECT id, gender, country_srt, lat, long
FROM wp_table"
$count = 0; // this is for $preJSON[] index
foreach( $wpdb->get_results( $sql ) as $key => $row ) {
// each column in your row will now be accessible like this:
// $my_column = $row->column_name;
// now we can do:
$value = $row->id;
$latitude = $row->lat;
$longitude = $row->long;
$gender = $row->gender;
$country = $row->country_srt;
$tooltip = array(
"content" => "HTML and stuff" . $gender . "more HTML and stuff" . $country
);
// now we can build a row of this information in our master array
$preJSON[$count] = array(
"value" => $value,
"latitude" => $latitude,
"longitude" => $longitude,
"tooltip" => $tooltip
);
// increment the index
++$count;
}
// after foreach
// send the whole array to json
$json = json_encode( $preJSON );
I believe this should be the basic gist of what you need

How do I remove nested object from an object in CakePHP?

CakePHP API returns result like this:
{
"status": "OK",
"themes": [
{
"Theme": {
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
}
]
}
I would like to ask, how can in remove nested Theme object to get result like this?:
{
"status": "OK",
"themes": [
{
"id": "20",
"user_id": "50",
"name": "dwdwdw",
"language_code_from": "cz",
"language_code_to": "en",
"type": "CUSTOM",
"created": "2014-10-19 15:36:05",
"count_of_cards": 0
}
]
}
Here is my CakePHP code:
$this->Theme->recursive = -1;
// GET USER ID
$themeData['user_id'] = $isSessionValid;
// GET ALL THEMES RELATED TO USER
$foundThemes = $this->Theme->find('all', array(
'conditions' => array(
'Theme.user_id' => $themeData['user_id'])
)
);
$themes = array();
// FOREACH THEMES AND GET COUNT FOR CARDS FOR EACH THEME
foreach($foundThemes as $foundTheme) {
// GET COUNT OF QUESTIONS FOR ACTUAL THEME
$countOfCards = $this->Theme->Card->find('count', array(
'conditions' => array(
'Card.theme_id' => $foundTheme['Theme']['id'])
)
);
// APPEND TO ACTUAL ARRAY
$foundTheme['Theme']['count_of_cards'] = $countOfCards;
array_push($themes,$foundTheme);
}
// SET SUCCESS RESPOSNSE
$this->set(array(
'status' => 'OK',
'themes' => $themes,
'_serialize' => array(
'status',
'themes',
)
));
Many thanks for any advice.
You can manipulate CakePHP's array formats using its built in Hash utility: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash
What I would do would be to flatten the results:
$results = Hash::flatten($results);
Your data array will end up as a single dimensional array looking like this:
$results = array(
'status' => 'OK'
'themes.0.Theme.id' => 20,
...
'themes.1.Theme.id' => 21,
...
);
You can then use string replace to remove "Theme" from your keys:
$keys = array_keys($results);
$keys = str_replace('Theme.', '', $keys);
Then you can use Hash::expand to get your original array, now formatted how you want:
$results = Hash::expand(array_combine($keys, array_values($results)));
I dont think CakePHP supports this. if you want to do this with an easy way check the Set Utility.
http://book.cakephp.org/2.0/en/core-utility-libraries/set.html

How to find a document by embedded item in MongoDB PHP

I have the next document in MongoDB:
Contest document:
{
"_id": ObjectId("502aa915f50138d76d11112f7"),
"contestname": "Contest1",
"description": "java programming contest",
"numteams": NumberInt(2),
"teams": [
{
"teamname": "superstars",
"userid1": "50247314f501384b011019bc",
"userid2": "50293cf9f50138446411001c",
"userid3": "50293cdff501384464110018"
},
{
"teamname": "faculty",
"userid1": "50247314f501384b0110100c",
"userid2": "50293cf9f50138446410001b",
"userid3": "50293cdff501384464000019"
}
],
"term": "Fall 2012"
}
Imagine that I have more than this document where users can register. I want to find all the contest that a user has registered. I have something like this so far:
$id = "50247314f501384b011019bc";
$user = array('userid1' => $id, 'userid2' => $id, 'userid3' => $id );
$team = array('teams' => $user);
$result =$this->collection->find($team);
return $result;
Could somebody help me with that?
Thank you.
------Solved------
$team = array('$or' => array(array('teams.userid1' => $id),
array('teams.userid2' => $id),
array('teams.userid3' => $id)
));
$result =$this->collection->find($team);
Your data structure is awkward to query because you have an array of embedded documents. With a slight change to the data you could make this easier to work with.
I've put the user IDs into an array:
{
"contestname": "Contest1",
"description": "java programming contest",
"numteams": 2,
"teams": [
{
"teamname": "superstars",
"members": [
"50247314f501384b011019bc",
"50293cf9f50138446411001c",
"50293cdff501384464110018"
]
},
{
"teamname": "faculty",
"members": [
"50247314f501384b0110100c",
"50293cf9f50138446410001b",
"50293cdff501384464000019"
]
}
],
"term": "Fall 2012"
}
You could then do the PHP equivalent find() for:
db.contest.find(
{'teams.members':'50247314f501384b011019bc'},
{'contestname':1, 'description':1}
)
Which would return the matching contests this user had entered:
{
"_id" : ObjectId("502c108dcbfbffa8b2ead5d2"),
"contestname" : "Contest1",
"description" : "java programming contest"
}
{
"_id" : ObjectId("502c10a1cbfbffa8b2ead5d4"),
"contestname" : "Contest3",
"description" : "Grovy programming contest"
}

Categories