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

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

Related

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

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

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

Create nested json object using php mysql

I have two tables, table 1 has 2 fields (question_pk, question_name) and table 2 has 4 fields(ans_pk, options, question_fk and right_answer). I want to create json like the following structure
{
"type": "quiz",
"name": "Brand Colors",
"description": "Can you identify these brands by the background color?",
"questions": [
{
"name": "Can you identify this color?",
"description": "#ea4c89",
"answers": [
{
"name": "Dribbble",
"description": "dribbble.png",
"weight": 1
},
{
"name": "Amazon",
"description": "amazon.png",
"weight": 0
},
{
"name": "Apple",
"description": "apple.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#3d9ae8",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 0
},
{
"name": "Dropbox",
"description": "dropbox.png",
"weight": 1
},
{
"name": "Wordpress",
"description": "wordpress.png",
"weight": 0
}
]
},
{
"name": "Can you identify this color?",
"description": "#c4302b",
"answers": [
{
"name": "Youtube",
"description": "youtube.png",
"weight": 1
},
{
"name": "Twitter",
"description": "twitter.png",
"weight": 0
},
{
"name": "Vimeo",
"description": "vimeo.png",
"weight": 0
}
]
}
]
}
MY PHP CODE
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("select * from $questions where sub_cat='$sub_cat_id' order by level_fk asc");
$json_response = array(); //Create an array
$i=1;
while ($row = mysql_fetch_array($result))
{
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("select * from $qus_ans where qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['options'] = $opt_fet['options'];
$row_array['right_ans'] = $opt_fet['right_ans'];
array_push($json_response,$row_array); //push the values in the array
}
$i++;
}
echo json_encode($json_response);
}
?>
And My Result I am getting json response like the following
[
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "45",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "40",
"right_ans": "0"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "35",
"right_ans": "1"
},
{
"qus_pk": "1",
"question": "Ten years ago, P was half of Q in age. If the ratio of their present ages is 3:4, what will be the total of their present ages?",
"options": "50",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "4 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "1 times",
"right_ans": "0"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "3 times",
"right_ans": "1"
},
{
"qus_pk": "2",
"question": "Father is aged three times more than his son Sunil. After 8 years, he would be two and a half times of Sunil's age. After further 8 years, how many times would he be of Sunil's age?",
"options": "5 times",
"right_ans": "0"
}
]
In my respose each time the question is repeated so how to avoid and if i want to achive the first json structure, in my PHP code what&where i need to make changes?. If any one knows help me.
Hi try this,
<?php
include '../config/config.php';
if(isset($_GET['sub_cat_id']))
{
$sub_cat_id = $_GET['sub_cat_id'];
$result = mysql_query("SELECT * FROM $questions WHERE sub_cat='$sub_cat_id' ORDER BY level_fk ASC");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['qus_pk'] = $row['qus_pk'];
$row_array['question'] = $row['question'];
$row_array['answers'] = array();
$qus_pk = $row['qus_pk'];
$option_qry = mysql_query("SELECT * FROM $qus_ans WHERE qus_pk=$qus_pk");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['answers'][] = array(
'options' => $opt_fet['options'],
'right_ans' => $opt_fet['right_ans'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
}
?>
I think this code is easier to figure out and by the way it uses mysqli ...
This is based on my own data structure, I am in the middle of something and I have no time a.t.m. to adapt it to the question but should easy to figure out how to adapt it to other structures :
$usersList_array =array();
$user_array = array();
$note_array = array();
$fetch_users = mysqli_query($mysqli, "SELECT
ID,
Surname,
Name
FROM tb_Users
WHERE Name LIKE 'G%'
ORDER BY ID") or die(mysqli_error($mysqli));
while ($row_users = mysqli_fetch_assoc($fetch_users)) {
$user_array['id'] = $row_users['ID'];
$user_array['surnameName'] = $row_users['Surname'].' '.$row_users['Name'];
$user_array['notes'] = array();
$fetch_notes = mysqli_query($mysqli, "SELECT
id,
dateIns,
type,
content
FROM tb_Notes
WHERE fk_RefTable = 'tb_Users' AND
fk_RefID = ".$row_users['ID'].""
) or die(mysqli_error($mysqli));
while ($row_notes = mysqli_fetch_assoc($fetch_notes)) {
$note_array['id']=$row_notes['id'];
$note_array['dateIns']=$row_notes['dateIns'];
$note_array['type']=$row_notes['type'];
$note_array['content']=$row_notes['content'];
array_push($user_array['notes'],$note_array);
}
array_push($usersList_array,$user_array);
}
$jsonData = json_encode($usersList_array, JSON_PRETTY_PRINT);
echo $jsonData;
Resulting JSON :
[
{
"id": "1",
"surnameName": "Xyz Giorgio",
"notes": [
{
"id": "1",
"dateIns": "2016-05-01 03:10:45",
"type": "warning",
"content": "warning test"
},
{
"id": "2",
"dateIns": "2016-05-18 20:51:32",
"type": "error",
"content": "error test"
},
{
"id": "3",
"dateIns": "2016-05-18 20:53:00",
"type": "info",
"content": "info test"
}
]
},
{
"id": "2",
"cognomeNome": "Xyz Georg",
"notes": [
{
"id": "4",
"dateIns": "2016-05-20 14:38:20",
"type": "warning",
"content": "georg warning"
},
{
"id": "5",
"dateIns": "2016-05-20 14:38:20",
"type": "info",
"content": "georg info"
}
]
}
]
A basic class to handle nesting tables into a php array.
PHP CLASS
// chain data into a php array, filtering by relation to parent, based on a structure definition array
// nest child data by relation to parent data
// assign a array label "arr_label" to child definition to define what key the filtered data will use
// assign a parent key "p_key" and a child key "c_key" to child definition to assign connection points from child to parent
// load array data to filter into "arr" key on child definition
class class_chain_filter
{
var $return_arr;
function __construct()
{
} // CONSTRUCTOR
// input a defined filter tree array and output a processed result
function chain_filter($filter_tree)
{
// can feed either a single record a set of rows...
if(!$this->is_assoc($filter_tree['arr']))
$this->return_arr = $filter_tree['arr']; // root for return array
else
$this->return_arr[] = $filter_tree['arr']; // force a numeric array so return is consistent.
$this->do_chain_filter( $filter_tree['next_arrs'], $this->return_arr );
return $this->return_arr;
} // $this->chain_filter($filter_tree) // public
function is_assoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
function do_chain_filter(&$tree_arr, &$final_arr)
{
$cur_final_node = &$final_arr;
if( !is_array($cur_final_node) )
return false;
// send the next_arrs
foreach($final_arr as $f_key => $f_arr)
{
$cur_final_node = &$final_arr[$f_key];
foreach($tree_arr as $n_key => $n_arr)
{
$cur_tree_node = $tree_arr[$n_key];
// $final_cur_el['arr_label'] = 'true';
$next_final_node = &$cur_final_node[$cur_tree_node['arr_label']];
// data up hombre
// filter out array elements not related to parent array
$result = $this->children_of_parent(
$cur_final_node,
$cur_tree_node['arr'],
$cur_tree_node['p_key'],
$cur_tree_node['c_key']
);
$next_final_node = $result;
// now recurse if we have more depths to travel...
if(!empty($cur_tree_node['next_arrs']))
$this->do_chain_filter($cur_tree_node['next_arrs'], $next_final_node);
}
}
} // this->function chain_filter(&$tree_arr, &$final_arr)
// take 2 arrays
// first array is an associative array.
// second array is an array of associative arrays.
// return children of second array that belong to parent array
function children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
{
// parent = a record
// child = multiple records
// filter out children that don't apply to parent.
// return the result
$parent_id = $arr_parent[$key_parent];
foreach($arr_children as $arr_child)
{
$child_id = $arr_child[$key_child];
if($child_id == $parent_id)
$return_arr[] = $arr_child;
}
if(!empty($return_arr))
return $return_arr;
} // this->children_of_parent($arr_parent, $arr_children, $key_parent, $key_child )
} // end. class class_chain_filter
LOAD UP SOME TABLES (USE YOUR OWN PREFERRED DB CLASS)
$areas = $db->get("SELECT * FROM areas");
$rooms = $db->get("SELECT * FROM rooms");
$exits = $db->get("SELECT * FROM exits");
DEFINE OUR RETURNED ARRAY TREE STRUCTURE
// predefine tree structure for generation
// structure definition array example...
$tree_arr = array (
"arr" => $areas, // root (can be multiple rows or a single record)
"next_arrs" => array ( // children
0 => array(
"arr" => $rooms, // array to filter against parent
"arr_label" => "rooms", // for the php array label
"p_key" => "id", // field name of parent // eg) id
"c_key" => "areaid", // this array's field name that links it to parent
"next_arrs" => array( // children
0 => array(
"arr" => $exits, // array to filter against parent
"arr_label" => "exits", // for the php array label
"p_key" => "id", // field name of parent / blank if root / eg) id
"c_key" => "roomid" // this array's field name that links it to parent
)
)
)
)
); // $tree_arr
NOW CREATE OBJECT AND PROCESS INTO DESTINATION ARRAY
$c = new class_chain_filter();
$return_arr = $c->chain_filter($tree_arr);
print_r($return_arr);
... AND THE OUTPUT SHOULD LOOK LIKE ...
Array (
[0] => Array
(
[id] => 1
[name] => New World
[author] => anon
[resetfreq] => 3
[rooms] => Array
(
[0] => Array
(
[id] => 1
[areaid] => 1
[name] => Entrance
[description] => The air is humid here.
[exits] => Array
(
[0] => Array
(
[id] => 1
[roomid] => 1
[toroomid] => 2
[direction] => n
[description] => A Hall
[keyid] => 1
)
[1] => Array
(
[id] => 5
[roomid] => 1
[toroomid] => 3
[direction] => s
[description] => Entrance
[keyid] =>
)
)
)
[1] => Array
(
[id] => 2
[areaid] => 1
[name] => A Corridor
[description] => Seems nothing is really going on in this room. Bland tapestry and nothing worth really hanging around for. From the west comes the sound of people training. To the east you can hear people practicing skills and abilities.
[exits] => Array
(
[0] => Array
(
[id] => 2
[roomid] => 2
[toroomid] => 1
[direction] => s
[description] => A Corridor
[keyid] =>
)
[1] => Array
(
[id] => 7
[roomid] => 2
[toroomid] => 4
[direction] => e
[description] => Practice Room
[keyid] =>
)
[2] => Array
(
[id] => 9
[roomid] => 2
[toroomid] => 5
[direction] => w
[description] => Training Room
[keyid] =>
)
[3] => Array
(
[id] => 11
[roomid] => 2
[toroomid] => 8
[direction] => n
[description] => A Bend
[keyid] =>
)
)
)
)
)
)
and then you could just json_encode the array to turn it from a PHP array into a JSON string

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

MongoDB request with the condition do not display

"bookName": "I've been discovered",
"bookGenre": {
"0": "Classics",
"1": "Fantasy",
"2": "Romance"
}
"bookName": "Doctor Who",
"bookGenre": {
"0": "Classics",
"1": "Biography"
}
"bookName": "I don't want to tread carefully",
"bookGenre": {
"0": "Classics",
"1": "Fantasy",
"2": "History"
}
I want to get all the books in the genre Classics, but excluding the genre Fantasy and History.
$genre = array("Classics");
$genreNot = array("Fantasy", "History");
$q = find(array("bookGenre" => array('$in' => $genre), "bookGenre" => array('$nin' => $genreNot)));
In this query, I get all my books, and the exception is not bringing the genre Fantasy and History does not work.
How to make a request to the excluded genre work?
Hmm you have got a fundamental problem with your arrays here:
$q = find(array("bookGenre" => array('$in' => $genre),
"bookGenre" => array('$nin' => $genreNot)));
You have duplicate keys for the same object so actually the only clause in this query that goes through is "bookGenre" => array('$nin' => $genreNot). I believe instead you can combine the $in and $nin:
$q = find(array(
"bookGenre" => array('$in' => $genre, '$nin' => $genreNot)
));
Like so.

Categories