How do i get this data in the proper format? - php

ok so i have this query
select ss.system_step_id, ss.step_number, cd.name, ssp.system_step_product_id, p.cost, ssp.class_id from system_step ss
join system as s on s.system_id=ss.system_id
join category_description as cd on cd.category_id=ss.sub_category_id
join system_step_product as ssp on ss.system_step_id=ssp.system_step_id
join product as p on p.product_id=ssp.product_id where s.system_id = 41
order by ss.step_number, ssp.class_id;
which yields this result
7 1 Screens 808 115.0000 1
7 1 Screens 809 381.9000 2
7 1 Screens 810 441.9000 3
8 2 Printers 811 112.3200 1
8 2 Printers 812 201.0400 2
8 2 Printers 813 202.8700 3
9 3 Cash Drawers 814 135.7000 1
9 3 Cash Drawers 815 86.5400 2
9 3 Cash Drawers 816 135.7000 3
Is there a way to turn this into a php array of three elements like this
Array
(
[0] => Array
(
[name] => "Screens"
[standard_product] => Array ([id] => 808, [price] => '115.0000')
[business_product] => Array ([id] => 809, [price] => '381.9000')
[premium_product] => Array ([id] => 810, [price] => '441.9000')
)
[1] => Array
(
[name] => "Printers"
[standard_product] => Array ([id] => 811, [price] => '112.3200')
[business_product] => Array ([id] => 812, [price] => '201.0400')
[premium_product] => Array ([id] => 813, [price] => '202.8700')
)
[2] => Array
(
[name] => "Cash Drawers"
[standard_product] => Array ([id] => 814, [price] => '135.7000')
[business_product] => Array ([id] => 815, [price] => '86.5400')
[premium_product] => Array ([id] => 816, [price] => '135.7000')
)
)
$sql = "select ss.system_step_id, ss.step_number, cd.name, ssp.system_step_product_id, p.cost, ssp.class_id, pd.name as product_name, pd.description from system_step ss join system as s on s.system_id=ss.system_id join category_description as cd on cd.category_id=ss.sub_category_id join system_step_product as ssp on ss.system_step_id=ssp.system_step_id join product as p on p.product_id=ssp.product_id join product_description as pd on pd.product_id=p.product_id where s.system_id = {$system['system_id']} order by ss.step_number, ssp.class_id;";
$result = mysql_query($sql);
$steps = array();
while($row_r = mysql_fetch_assoc($result)){
$steps[] = $row_r;
}
so steps is the the full array with 9 elements
As you can see the only thing of note is the class_id 1 is standard_product class_id 2 is business_product and class_id 3 is premium_product

You can fetch fill a multi-dimensional array while fetching the SQL result or split into several SQL commands and therefore build up your array (1st fetching the names, than the products with values of every name).
I do not know which you prefer but as you have a large join splitting the SQL might not be the worst in terms of readability of your code. Performance impact may vary.

Methinks this will do it
<?php
$finalArray = array();
$nameArray = array('Screens', 'Printers', 'Cash Drawers');
foreach ($nameArray as $name) {
while ($row = mysql_fetch_assoc($result)) {
if ($row['name'] == $name) {
if ($row['class_id'] == 1) {
$standard = array('id' => $row['system_step_product_id'], 'price' => $row['cost']);
}
else if ($row['class_id'] == 2) {
$business = array('id' => $row['system_step_product_id'], 'price' => $row['cost']);
}
else if ($row['class_id'] == 3) {
$premium = array('id' => $row['system_step_product_id'], 'price' => $row['cost']);
}
}
}
array_push($finalArray, array('name' => $name, 'standard_product' => $standard, 'business_product' => $business, 'premium_product' => $premium,));
}
?>
Hopefully I got all the column names right.
This is what I tested it off of and I get the correct output http://codepad.org/yjU3gxbB
The only thing you may what to change is creating the name array dynamically
while ($row = mysql_fetch_assoc($result)) {
array_push($nameArray, $row['name']);
}
$nameArray = array_unique($nameArray);
However, PHP doesn't like it when you do a mysql_fetch_assoc twice on the same query. You might want to do another query where you only select the cd.name

Related

store all leave to array

I am trying to fetch all employee leave data to an array. But first leave data of my employee is replacing by last leave data. I do not want that.
my data set:
id | emp_id | leave_from | leave_to
2894 886 2019-11-26 2019-11-27
2896 1970 2019-11-20 2019-11-24
2897 1016 2019-11-23 2019-11-23
2898 1870 2019-11-10 2019-11-10
2899 1895 2019-11-09 2019-11-11
2900 1895 2019-11-23 2019-11-23
2901 287 2019-11-27 2019-11-30
my sql query:
$leave_sql = "SELECT l.* FROM 0_employee e right join (SELECT * FROM 0_leave_ledger WHERE (leave_approved_from && leave_approved_to BETWEEN '".$fisrt_date."' AND '".$last_date."' )) l ON l.emp_id = e.emp_id where e.inactive=0";
$leave = get_tb($leave_sql);
$leave_date = array();
foreach ($leave as $leave_d) {
$leave_date[$leave_d["emp_id"]]['type'] = $leave_d["leave_type"];
$leave_date[$leave_d["emp_id"]]['lto'] = $leave_d["leave_approved_to"];
$leave_date[$leave_d["emp_id"]]['lfrom'] = $leave_d["leave_approved_from"];
}
let's look emp_id 1895.It has two rows in my data set. So I am expecting to insert those two rows in my array. But I am getting only last rows of data in my array.
my expecting output from $leave_date is:
[1895] => Array ( [type] => 4 [lto] => 2019-11-09 [lfrom] => 2019-11-11 )
[1895] => Array ( [type] => 4 [lto] => 2019-11-23 [lfrom] => 2019-11-23 )
but I am getting only
[1895] => Array ( [type] => 4 [lto] => 2019-11-23 [lfrom] => 2019-11-23 )
Your problem is that you have an employee who has taken multiple leaves, and the entries for each leave overwrite any previous ones in your array because they have the same array index. You need to change your data structure to allow for that. Try something like this:
$leave_date = array();
foreach ($leave as $leave_d) {
$leave_date[$leave_d["emp_id"]][] = array(
'type' => $leave_d["leave_type"],
'lto' => $leave_d["leave_approved_to"],
'lfrom' => $leave_d["leave_approved_from"]
);
}
For your sample data, this will give you something like
[1895] => Array (
[0] => Array ( [type] => 4 [lto] => 2019-11-09 [lfrom] => 2019-11-11 )
[1] => Array ( [type] => 4 [lto] => 2019-11-23 [lfrom] => 2019-11-23 )
)
The structure of your array $leave_date means it can only store one set of leave data per emp_id. When you iterate, it first fills up with the first leave record, and then the second iteration it gets replaced. If you were to put a print_r() at the end of your foreach you would see this happen for each iteration.
What you may want to do is try something like this:
foreach ($leave as $leave_d) {
$record = [
'type' => $leave_d["leave_type"],
'lto' => $leave_d["leave_approved_to"],
'lfrom' => $leave_d["leave_approved_from"],
]
if(array_key_exists($leave_d['emp_id'], $leave_date) {
$leave_date[$leave_d['emp_d']][] = $record;
} else {
$leave_date[$leave_d['emp_d'] = [$record];
}
This way, $leave_date[1234] will always be an array of leave records.

How to take value from First array and generate second array and put the second array in the first array?

I have tried many ways to do this but no luck. I'm trying to take value from First array and generate second array and put the second array in the first array.
The code that I have now, generate the first array, in this array I have column called prereq_id I need to take this value and match it with courses table to bring its information in the courses table course_id=prereq_id. Any help would be highly appreciated
The array output is like this right now
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
php
$result2 = $mysqli->query("SELECT *
FROM curriculumcourses
INNER JOIN courses ON curriculumcourses.course_id = courses.course_id
LEFT JOIN prerequisites ON courses.course_id=prerequisites.course_id
WHERE curriculum_id='$ids' ");
?>
<?php
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result2->fetch_assoc();
}
echo "<pre>";
print_r($rows);
echo "</pre>";
The result I need look like this
[course_id] => 2
[curriculum_id] => 1
[set_number] => 0
[course_code] => GCIS 516
[course_name] => Data-Centric Concepts and Methods
[credits] => 3
[semester_ava] => 2
[prereq_id] => 10
[set] => 3
[course_code] => GCIS 508
[course_name] =>Database Management Systems
[credits] => 3
[semester_ava] => 1

check if a value exist in array from database query

I am trying to build a website that will display the text in multiple languages.
I have a table 'text' with all the languages. If the text does not exist in the chosen language it has to display the default language.
query SELECT * FROM text WHERE TextId = 10
results in
Id TextId LanguageId Text
10 10 1 first name
13 10 2 名前
If I r_print this result I get something like this
Array ( [0] => Array ( [0] => 10 [Id] => 10 [1] => 10 [TextId] => 10 [2] => 1 [LanguageId] => 1 [3] => first name [Text] => first name )
[1] => Array ( [0] => 13 [Id] => 13 [1] => 10 [TextId] => 10 [2] => 2 [LanguageId] => 2 [3] => 名前 [Text] => 名前 ) )
How can I check that LanguageId 2 exist in this array ?
the problem is that it is possible that TextId 2 and Id 2 can also exist in this array.
Is this possible to do with in_array()?
Here is a function that can check if LanguageId equals a special value .
function isLanguageIdExists($yourArray , $LanguageId){
$exists=false;
foreach($yourArray as $array){
if(isset($array['LanguageId'])&& $array['LanguageId'] == $LanguageId){
$exists=true;break;
}
}
return $exists;
}
$exist = isLanguageIdExists($yourArray , 2);//return true or false
You can check by isset the key and match the value in php.
$dataArray = array(
0 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1),1 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1)
);
foreach($dataArray as $value) {
if(isset($value['LanguageId']) && $value['LanguageId'] == 2) {
echo 'language ID 2 is available';
}
}
Working Demo
After giving this some more thought I came up with a maybe not so elegant solution.
Instead of getting an array back I modified the SQL Query to give one row back with the default language (English) and a user selected language (Japanese).
It uses two left joins. This shows that I received (some) training in SQL but am really not at ease with multidimensional arrays.
Query
def_text = text in default language
usr_text = text in user chosen language
$table01 = "text";
$query="SELECT $table01.TextId,
text_def.Text as def_text,
text_usr.Text as usr_text
FROM $table01
LEFT JOIN $table01 as text_def ON $table01.TextId = text_def.TextId AND text_def.LanguageId = $_SESSION[default_language]
LEFT JOIN $table01 as text_usr ON $table01.TextId = text_usr.TextId AND text_usr.LanguageId = $_SESSION[language]
WHERE $table01.TextId=$mess;";
after getting back the results it is easy to check with isset() or empty() to see if the text is available in the user selected language

How to count the number of same values in php or mysql

p1 p2 p3 p4 p5 p6 p7 p8
---------------------------------------------------------------------------------------
1414 1414 1417 1417 1422,1421 1422,1421 1422,1421 1422,1421
The above table has 8 columns in which the adjacent columns having same values. How to count the number of columns based on the column values in php or in mysql..
For Eg :
for 1414---values are p1,p2 and count is 2
for 1422,1421--- values are p5,p6,p7,p8 and count is 4.
Can any one help me in this..
Array
(
[0] => Array
(
[period] => p1
[subject] => 1434
[nop] => 1
)
<b>
**[1] => Array
(
[period] => p2
[subject] => 1440,1439
[nop] => 1
)
[2] => Array
(
[period] => p2,p3
[subject] => 1440,1439
[nop] => 2
)**
</b>
[3] => Array
(
[period] => p2,p3,p4
[subject] => 1440,1439
[nop] => 3
)
[4] => Array
(
[period] => p5
[subject] => 1442
[nop] => 1
)
[5] => Array
(
[period] => p6
[subject] => 1442
[nop] => 1
)
[6] => Array
(
[period] => p7
[subject] => 1442
[nop] => 1
)
)
I have got the above array.. how to remove the above highlighted values in the above array from it.
suppose your $row has reesult of table
$your_val = '1414'; // for eg 1414
$result_col = ""; // will contain you columns
$result_count = 0; // will contain your count
// $row has the each column value when you fetch from database eg $row['p1'] = 1414
foreach($row as $key=>$val)
{
if($val==$your_val)
{
$result_count += 1;
if($result_text=="")
{
$result_col = $key;
}
else
{
$result_col = $result_col.",".$key;
}
}
}
echo "values are ".$result_col." and count is ".$result_count; // output
You can do it with MySQL:
SELECT
IF(p1='1414',1,0) + IF(p2='1414',1,0)+ IF(p3='1414',1,0) + IF(p4='1414',1,0) + IF(p5='1414',1,0) + IF(p6='1414',1,0) + IF(p7='1414',1,0) + IF(p8='1414',1,0) AS cnt
FROM your_table;
If you are using PHP to access the databasem, you can replace the '1414' with a variable to count the occurences of the variable's value.

php dynamically create multi dimensional array

I am writing a php script to extract some data from a MYSQL db, then I want to take that data and store it into a two dimensional array. Thinking of it normally, if I use code like this
$test = array();
$test[0]=array();
$test[0]['hello']='hello';
$test[1]=array();
$test[1]['hello']='hello';
$test[2]=array();
$test[2]['hello']='hello';
print_r($test);
the output will be:
Array ( [0] => Array ( [hello] => hello ) [1] => Array ( [hello] => hello ) [2] =>
Array ( [hello] => hello ) )
which is how I want my output to be
so this is what I do in my script
So basically in my database I have table with standings for a women's league and the columns are
team_name, played, won, drawn, lost, for, against, points
All the connections have been taken care of successfully, below is my query
$get_ladies_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_ladies` order by pos";
An important point to not before I show the next code is that, there are 2 other standings tables, men_senior and men_intermediate with the same structure but obviously only the data changes, below are the two queries just incase
$get_mens_inter_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_inter` order by pos";
$get_mens_senior_query = "SELECT
`team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_senior` order by pos";
Now I create 3 arrays which I want to hold standings seperately for the ladies, mens senior, mens intermediate
$standings_ladies = array();
$standings_men_inter = array();
$standings_men_senior = array();
The data I want displayed in the array is like so
array(0=>array(team_name,wins,drawn,lost,for,against,points)
1=>array(team_name,wins,drawn,lost,for,against,points)) and so on
Now since I wanted to create the multidimensional arrays of standings for all 3 categories, I could have run the queries in 3 separate while loops altough I thought, I could accomplish the same result in 1 and i felt it would help improve performance. If its better to use 3 while loops, please let me know, what I tried is below.
//I run the 3 queries and store them in the given variables
$result_mens_senior = mysqli_query($link,$get_mens_senior_query);
$result_mens_inter = mysqli_query($link,$get_mens_inter_query);
$result_ladies= mysqli_query($link, $get_ladies_query);
//I want to create 1 while loop so based of the results returned from the 3
//queries so based on the results returned from the 3 queries,
//I get the max number of times I want the query to run
$ladies_boundary = mysqli_num_rows($result_ladies);
$mens_senior_boundary = mysqli_num_rows($result_mens_senior);
$mens_inter_boundary = mysqli_num_rows($result_mens_inter);
$max_size = max(array($ladies_boundary,$mens_senior_boundary,$mens_inter_boundary));
//set an index to start from 0
$index = 0;
//I will only show the example for 1 of the arrays but you get an idea
that this issue will occur for all
while ($index < $max_size)
{
//first, everytime the loop is entered, we need the next row to be fetched
$standings_men_inter_table = mysqli_fetch_assoc($result_mens_inter);
$standings_ladies_table = mysqli_fetch_assoc($result_ladies);
//there is a high chance that the other two tables return a different row size
//so its best to check that we do not go beyond
if($index < $mens_senior_boundary)
{
//we fetch the rows every time we enter the block
$standings_men_senior_table = mysqli_fetch_assoc($result_mens_senior);
//then, this is how I attempt at creating the 2 dimensional array
array_push($standings_men_senior, array(
$standings_men_senior_table['team_name'],
$standings_men_senior_table['played'],
$standings_men_senior_table['won'],
$standings_men_senior_table['drawn'],
$standings_men_senior_table['lost'],
$standings_men_senior_table['for'],
$standings_men_senior_table['against'],
$standings_men_senior_table['points']));
}
//incrementing index each time the loop runs
$index++;
}
Then finally, I just want to print what I think is the array but get this, attached image, hope you can see it clearly
Just to investigate even further, every time, the 'if' block is entered, I just commented everything out and just put this to see what was being returned
if($index < $mens_senior_boundary)
{
print_r(mysqli_fetch_assoc($result_mens_senior));
}
The output I got was almost 90% what I need
Array
([team_name] => Morley Gaels [played] => 8 [won] => 6 [drawn] => 2
[lost] => 0 [for] => 110 [against] => 83 [points] => 14 )
Array ( [team_name] => Southern Districts [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 104 [against] => 98 [points] => 8 )
Array ( [team_name] => St Finbarrs [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 107 [against] => 99 [points] => 8 )
Array ( [team_name] => Western Shamrocks [played] => 8 [won] => 3 [drawn] => 0
[lost] => 5 [for] => 96 [against] => 88 [points] => 6 )
Array ( [team_name] => Greenwood [played] => 8 [won] => 1 [drawn] => 1
[lost] => 9 [for] => 82 [against] => 109 [points] => 3 )
What I need is for example:
Array(0=>Array
([team_name] => Morley Gaels [played] => 8 [won] => 6 [drawn] => 2
[lost] => 0 [for] => 110 [against] => 83 [points] => 14 )
1=>Array
([team_name] => Southern Districts [played] => 8 [won] => 3 [drawn] => 2
[lost] => 3 [for] => 104 [against] => 98 [points] => 8 )..... so on);
My questions are
What is wrong with my code and what is the correct way to dynamically create
multidimensional arrays in php ?
Is there something I have not understood about how mysql_fetch_assoc works and how it returns ?
Anything to improve, anything I am doing wrong ?
I appreciate your time, than you for reading it, I tried to be as detailed as I can about what I have tried.
Thank You.
Try this
After you do this:
$result_mens_senior = mysqli_query($link,$get_mens_senior_query);
$result_mens_inter = mysqli_query($link,$get_mens_inter_query);
$result_ladies= mysqli_query($link, $get_ladies_query);
just do this
while ($standings_men_senior[] = mysqli_fetch_assoc($result_mens_senior)){}
while ($standings_men_inter[] = mysqli_fetch_assoc($result_mens_inter)){}
while ($standings_ladies[] = mysqli_fetch_assoc($result_ladies)){}
Basically all of the posted code should be able to be replaced with:
<?php
$ladies_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_ladies` order by pos";
$inter_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_inter` order by pos";
$senior_query = "SELECT `team_name`, `played`, `won`, `drawn`, `lost`, `for`, `against`, `points`
FROM `standings_men_senior` order by pos";
$ladies_stmt = mysqli_query($link, $ladies_query) || die ("Couldn't get Ladies"); // reminds me of high school
$inter_stmt = mysqli_query($link, $inter_query) || die ("Couldn't get Inter");
$senior_stmt = mysqli_query($link, $serior_query) || die ("Couldn't get Seniors");
$standings_men_senior = array();
$standings_men_inter = array();
$standings_ladies = array();
while ($row = mysqli_fetch_assoc($senior_stmt)){
$standings_men_senior[] = $row;
}
while ($row = mysqli_fetch_assoc($inter_stmt)){
$standings_men_inter[] = $row;
}
while ($row = mysqli_fetch_assoc($ladies_stmt)){
$standings_ladies[] = $row;
}
Don't try to put everything in a single loop, it significantly reduces your code clarity and will give you little to no gain in performance, there is a term for this and it's called micro-optimization, and you should never do it unless it is really necessary (a bottleneck on a large site).
Now, what I suggest to you is to remake your loop and make it as clear as possible as to how data is manipulated.
The most important thing in your case is to debug, print_r the content of your arrays on every step of the process to check what it contains, from the database to the end of your code, you will find where the problem is.

Categories