How to use multidimensional array in mysql query with php? - php

I am using three tables and one query in mysql in order to retrieve a particular user.
I am getting exactly what I want from the query, but it's not formatted in the right way.
My query:
public function get_all_payslips()
{
$empid = $this->session->userdata('EMPLOYEE_ID');
$orgid = $this->session->userdata('CURRENT_ORG_ID');
$where = "EMPLOYEE_ID ='".$empid."' ";
$response = array();
$queryString = "SELECT
em.EMPLOYEE_ID,
em.EMPLOYEE_NAME
FROM
uk_new_salary_slip assd,
employee_master em
WHERE
em.".$where."
GROUP BY em.EMPLOYEE_ID
order by em.EMPLOYEE_NAME asc";
$query = $this->db->query($queryString);
foreach ($query->result() as $data)
{
$result = array();
$result['EMPLOYEE_NAME'] = $data-> EMPLOYEE_NAME;
$queryString = "SELECT
mo.months,
MONTH((assd.pay_period)) as monthss,
YEAR((assd.pay_period)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(assd.id)) as action,
GROUP_CONCAT(DISTINCT(assd.ORG_ID)) as org
FROM
uk_new_salary_slip assd,
employee_master em,
months mo
WHERE
assd.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((assd.pay_period))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$queryString1 = "SELECT
mo.months,
MONTH((germany.pay_from)) as monthss,
YEAR((germany.pay_from)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(germany.id)) as action,
GROUP_CONCAT(DISTINCT(germany.ORG_ID)) as org
FROM
new_germany_salary_slip germany,
employee_master em,
months mo
WHERE
germany.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((germany.pay_from))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$queryString2 = "SELECT
mo.months,
MONTH((poland.pay_from)) as monthss,
YEAR((poland.pay_from)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(poland.id)) as action,
GROUP_CONCAT(DISTINCT(poland.ORG_ID)) as org
FROM
new_poland_salary_slip poland,
employee_master em,
months mo
WHERE
poland.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((poland.pay_from))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$query1 = $this->db->query($queryString);
$query2 = $this->db->query($queryString1);
$query3 = $this->db->query($queryString2);
$children = array();
foreach ($query1->result() as $data1)
{
$yearArray = array();
$yearArray['month'] = $data1->months;
$yearArray['year'] = $data1->PAY_YEAR;
$yearArray['org'] = $data1->org;
$yearArray['action'] = $data1->action;
array_push($children, $yearArray);
}
foreach ($query2->result() as $data2)
{
$yearArray = array();
$yearArray['month'] = $data2->months;
$yearArray['year'] = $data2->PAY_YEAR;
$yearArray['org'] = $data2->org;
$yearArray['action'] = $data2->action;
array_push($children, $yearArray);
}
foreach ($query3->result() as $data3)
{
$yearArray = array();
$yearArray['month'] = $data3->months;
$yearArray['year'] = $data3->PAY_YEAR;
$yearArray['org'] = $data3->org;
$yearArray['action'] = $data3->action;
array_push($children, $yearArray);
}
$result['children'] = $children;
array_push($response, $result);
}
return $response;
}
If in the month array the year is same then the IN action value should be 4,2 . If you see in object 0th and 4th month and year is the same so both object's action values should be in one row, and similarly its org value should be org:40,47 respectively.
{month:"FEBRUARY", year:"2018",org:"40,47",action:"4,2"}
I want the data to be formatted like this but in my case it shows different rows for each action.

Array push just adds elements on to the end of the array. It is not what you want. You want to essentially compound elements of the same year and month. To do that we can assign that as the 1st sub array key and simply append the array values to org and action:
$output = array();
foreach ($query1->result() as $data1) {
$key = $data1->PAY_YEAR . $data1->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data1->months;
$output[$key]['year'] = $data1->PAY_YEAR;
}
$output[$key]['org'][] = $data1->org;
$output[$key]['action'][] = $data1->action;
}
foreach ($query2->result() as $data2) {
$key = $data2->PAY_YEAR . $data2->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data2->months;
$output[$key]['year'] = $data2->PAY_YEAR;
}
$output[$key]['org'][] = $data2->org;
$output[$key]['action'][] = $data2->action;
}
foreach ($query3->result() as $data3) {
$key = $data3->PAY_YEAR . $data3->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data3->months;
$output[$key]['year'] = $data3->PAY_YEAR;
}
$output[$key]['org'][] = $data3->org;
$output[$key]['action'][] = $data3->action;
}
echo '<pre>';
print_r(array_keys($output));

Related

Is there a way I can sort this array

I want to sort a returned value from a while loop here is my code
public function Getter($stream){
$sql1 = "SELECT reg_no FROM hs_registration ";
$sql1.= "JOIN hs_students USING(reg_no) WHERE class_id = 2";
$result1 = $database->query($sql1);
$num1 = $database->num_rows($result1);
if($num1 > 0){
$records = array();
$number_of_sub = getNoSub();
while($row = mysqli_fetch_array($result1)){
//return individual score
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$records[] = number_format($flyAvg,2).' '.$row['reg_no'];
}
}
return $records;
}
$averages = Getter($stream);
foreach ($averages as $avg){
echo $avg
}
Please, I want to sort the output based on the avg with the students reg_no appended to it
Output
54.20 FMS34
91.00 FMS51
72.16 FMS64
44.81 FMS23
68.52 FMS30
48.65 FMS37
My desired output is
Output
91.00 FMS51
72.16 FMS64
68.52 FMS30
54.20 FMS34
48.65 FMS37
44.81 FMS23
If your leading numbers are always two digits, then a decimal point, the two digits, then rsort($records); would suffice.
If they might be anything else, then keep a separate sorting array, then use array_multisort() to modify the $records.
public function Getter($stream): array
{
$sql = "SELECT reg_no
FROM hs_registration
JOIN hs_students USING(reg_no)
WHERE class_id = 2";
$flyAvgs = [];
$records = [];
$number_of_sub = getNoSub();
foreach ($database->query($sql) as $row) {
$total = $this->totalScoreSpreadSheet($row['reg_no'], $stream);
$flyAvg = $total / $number_of_sub;
$flyAvgs[] = $flyAvg;
$records[] = number_format($flyAvg, 2) . ' ' . $row['reg_no'];
}
array_multisort($flyAvgs, SORT_DESC, $records);
return $records;
}

Combine three array into one inside foreach

$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields
FROM categories
WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field = str_replace("/","",$field); /* Delete all '/' */
print_r($field);
}
Inside foreach loop, my query returns something like that /7/,/13/,/24/ from fields for every turn, then I clean them from slashes and commas.
My goal is collect all that arrays inside one array.
I tried to create an empty array outside of foreach and sum all in it but it returned empty.
You have to be define $filed as a array before foreach loop. now you can store value into $filed. note that you have to multidimensional array required to store value.
$cats_array = array(1,7,28);
$field = array();
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field1 = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field[] = str_replace("/","",$field1); /* Delete all '/' */
}
print_r($field);
I don't understand why do you store the fields like that, but here is a possible solution:
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
preg_match_all('/\/(\d+)\//', $cat_field->fields, $matches);
if (!empty($matches[1])) {
$fields = array_merge($fields, $matches[1]);
}
}
print_r($fields);
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id= $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); // Explode ',' from '/'3'/,'
$field = str_replace("/", "", $field);
$fields[] = $field;
}
print_r($fields);

Array problems with JSON in PHP

I'm trying to output a JSON feed in PHP and I keep having an issue where the second result in the JSON feed includes the results of the first as well.
Source below, and output:
Source
function fetch_tour_list($tourID) {
include('../inc/conn.php');
$query = mysqli_query($conn,"SELECT * FROM ticket_tour_dates WHERE TourID = $tourID");
while($result = mysqli_fetch_array($query)) {
$date['date'] = $result['Date'];
$venueID = $result['VenueID'];
$venue_query = mysqli_query($conn,"SELECT * FROM ticket_venues WHERE ID = $venueID");
while($venue_result = mysqli_fetch_array($venue_query)) {
$venue['id'] = $venue_result['ID'];
$venue['name'] = $venue_result['Name'];
$venue['location'] = $venue_result['Location'];
$venue['latitude'] = $venue_result['Lat'];
$venue['longitude'] = $venue_result['Long'];
$venues[] = $venue;
}
$date['venue'] = $venues;
$dates[] = $date;
}
echo json_encode($dates);
mysqli_close($conn);
}
Output
[{"date":"2013-07-29","venue":[{"id":"1","name":"The Gramercy","location":"New York City","latitude":"50.00000000","longitude":"50.00000000"}]},{"date":"2013-08-02","venue":[{"id":"1","name":"The Gramercy","location":"New York City","latitude":"50.00000000","longitude":"50.00000000"},{"id":"2","name":"The Troubadour","location":"Chicago","latitude":"20.00000000","longitude":"25.00000000"}]}]
Add the following line before the inner while loop:
$venues = array();

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

Structure of php JSON output

this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...

Categories