php dynamically create multi dimensional array - php

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.

Related

Display unique results and count duplicate results multi-dimentional array

Here is my multi-dimensional array:
Array
(
[0] => Array
(
[H2H_Id] => T32
[Team1_Id] => T4
[Team1] => Juan Arraya - Max LePivert
[Team2_Id] => T205
[Team2] => Marco Grangeiro - Jeff Morneau
[Winners_Id] => T4
[MatchUps_Id] => M32
)
[1] => Array
(
[H2H_Id] => T39
[Team1_Id] => T205
[Team1] => Marco Grangeiro - Jeff Morneau
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T205
[MatchUps_Id] => M32
)
[2] => Array
(
[H2H_Id] => T9
[Team1_Id] => T3
[Team1] => Marco Grangeiro - George Wilkinson
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T4
[MatchUps_Id] => M9
)
)
I want the output to be:
Juan Arraya - Max LePivert 1 vs. 1 Marco Grangeiro - Jeff Morneau
Juan Arraya - Max LePivert 1 vs. 0 Marco Grangeiro - George Wilkinson
So basically, I want to display the different match ups separately by using MatchUps_Id and print the names of the teams Team1 and Team2. Based on the Winners_Id I want to add a counter to keep track of the wins per team per match up.
Keep in mind that these results are coming from user inputs which will make the multi-dimensional array different every time I request input from the user passed on by field1 and field2.
This is what I have so far in code:
$query2 = "SELECT HeadToHead.H2HNo H2H_Id, H2HTeam1Id Team1_Id, H2HTeam1 Team1, H2HTeam2Id Team2_Id, H2HTeam2 Team2, WinnersId Winners_Id, MatchUps.MatchUpsNo MatchUps_Id
FROM HeadToHead
JOIN MatchUps ON HeadToHead.MatchUpsNo=MatchUps.MatchUpsNo
WHERE ((H2HTeam1 LIKE '%$field1%' OR H2HTeam2 LIKE '%$field1%') AND (H2HTeam1 LIKE '%$field2%' OR H2HTeam2 LIKE '%$field2%'))";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows($result2);
$arr2 = array();
if($num2 > 0) {
while($row2 = mysql_fetch_assoc($result2)) {
$arr2[] = $row2;
}
}
I get the desired results from the code above.
I think I have done a lot of research on this matter but what I am trying to accomplish seems to be different than what is out there.
Any help is much appreciated.
You can group the matchups together by 'MatchUps_Id' like this:
foreach ($arr2 as $match) {
// create some short ids to make the next part more readable
$id = $match['MatchUps_Id'];
$t1 = $match['Team1_Id'];
$t2= $match['Team2_Id'];
if (!isset($matchups[$id][$t1]['name'])) {
// initialize if this matchup has not yet been created
$matchups[$id][$t1]['name'] = $match['Team1'];
$matchups[$id][$t2]['name'] = $match['Team2'];
$matchups[$id][$t1]['wins'] = (int) ($match['Winners_Id'] == $match['Team1_Id']);
$matchups[$id][$t2]['wins'] = (int) ($match['Winners_Id'] == $match['Team2_Id']);
} else {
// increment wins if the matchup already exists
$matchups[$id][$t1]['wins'] += $match['Winners_Id'] == $match['Team1_Id'];
$matchups[$id][$t2]['wins'] += $match['Winners_Id'] == $match['Team2_Id'];
}
}
Using $t1 and $t2 as second-level keys allows you to increment the win count for respective teams without needing to know which one is which. The expression $match['Winners_Id'] == $match['Team1_Id'] returns a boolean, which will be implicitly cast to an integer 0 or 1 when used with +=, but must be explicitly cast using (int) when initializing.
After you have grouped your array and counted the wins, you can output the results like this:
foreach ($matchups as $matchup) {
list($a, $b) = array_values($matchup);
echo "$a[name] $a[wins] vs. $b[wins] $b[name]<br>";
}

php mysql check if vendor has 3 low consecutive ratings

on my ratings table for my software i have 4 fields.
id autoincrement
rvid vendor id
ratedate date of rating
rating the actual numeric rating
I have done alot with it over the last few months but this time im stumped and i cant get a clear picture in my head of the best way to do this. What i am trying to do is find out if the vendor has had 3 low 'consecutive' ratings. If their last three ratings have been < 3 then i want to flag them.
I have been playing with this for a few hours now so i thought i would ask (not for the answer) but for some path direction just to push me forward, im stuck in thought going in circles here.
I have tried GROUP BY and several ORDER BY but those attempts did not go well and so i am wondering if this is not a mysql answer but a php answer. In other words maybe i just need to take what i have so far and just move to the php side of things via usort and the like and do it that way.
Here is what i have so far i did select id as well at first thinking that was the best way to get the last consective but then i had a small breakthrough that if they have had 3 in a row the id does not matter, so i took it out of the query.
$sql = "SELECT `rvid`, `rating` FROM `vendor_ratings_archive` WHERE `rating` <= '3' ORDER BY `rvid` DESC";
which give me this
Array
(
[0] => Array
(
[rvid] => 7
[rating] => 2
)
[1] => Array
(
[rvid] => 5
[rating] => 1
)
[2] => Array
(
[rvid] => 5
[rating] => 0
)
[3] => Array
(
[rvid] => 5
[rating] => 3
)
)
this is just just samples i tossed in the fields, and there are only 4 rows here where as in live it will be tons of rows. But basically this tells me that these are the vendors that have low ratings in the table. And that is where i get stumpted. I can only do one sort in the query so that is why i am thinking that i need to take this and move to the php side to finish it off.
I think i need to sort the elements by rvid with php first i think, and then see if three elements in a row are the same vender (rvid).
Hope that makes sense. My brain hurts lol...
update - here is all of the table data using *
Array
(
[0] => Array
(
[id] => 7
[rvid] => 7
[ratedate] => 2016-05-01
[rating] => 2
)
[1] => Array
(
[id] => 8
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 1
)
[2] => Array
(
[id] => 6
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 0
)
[3] => Array
(
[id] => 5
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 3
)
)
Here's one way you can begin approaching this - completely in SQL:
Get the last rating for the vendor. ORDER BY date DESC, limit 1.
Get the second to last rating for the vendor. ORDER BY date DESC, limit 1, OFFSET 1.
Then write a query that does a LEFT join of the first two tables. You will have a dataset that has three columns:
vendor id
last rating
second to last rating
Then you can write an expression that says "if column1 is <3 and column2 < 3, then this new column is true"
You should be able to extend this to three columns relatively easily.
Here is what a came up with to solve this riddle. I think explaining it on here helped as well as Alex also helped as he keyed my brain on using the date. I first started looking at using if statment inside of the query and actually that got my brain out of the box and then it hit me what to do.
It is not perfect and certainly could use some trimming to reduce the code, but i understand it and it seems to work, so that is par for me on this course.
the query...
$sql = "SELECT `rvid`, `ratedate`,`rating` FROM `vendor_ratings_archive` WHERE `rating` <= '3' ORDER BY `ratedate`, `rvid` DESC";
which gives me this
Array
(
[0] => Array
(
[rvid] => 7
[ratedate] => 2016-05-01
[rating] => 2
)
[1] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 1
)
[2] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 0
)
[3] => Array
(
[rvid] => 5
[ratedate] => 2016-05-01
[rating] => 3
)
)
notice how vendor (rvid) 5 is grouped together which is an added plus.
next a simple foreach to load a new array
foreach($results as $yield)
{
$rvidarray[] = $yield['rvid'];
}//close foreach
which gives me this
Array
(
[0] => 7
[1] => 5
[2] => 5
[3] => 5
)
then we count the array values to group dups
$rvidcounter = array_count_values($rvidarray);
which results in this
Array(
[7] => 1
[5] => 3
)
so now vender 7 as 1 low score and vendor 5 has 3 low scores and since they were already sorted by date i know that its consecutive. Well it sounds good anyway lol ")
then we create our final array with another foreach
foreach($rvidcounter as $key => $value)
{
//anything 3 or over is your watchlist
if($value > 2)
{
$watchlist[] = $key; //rvid number stored
}
}//close foreach
which gives me this
Array
(
[0] => 5
)
this was all done in a service function. So the final deal is everyone in this array has over 3 consecutive low ratings and then i just use a returned array back in my normal php process file and grab the name of each vender by id and pass that to the html and print out the list.
done...
please feel free to improve on this if you like. I may or may not use it because the above code makes sense to me. Something more complicated may not make sense to me 6 mos from now lol But it would be interesting to see what someone comes up with to shorten the process a bit.
Thanks so much and Happy Coding !!!!!
Dave :)
You could do it in SQL like that:
SET #rvid = -1;
SELECT DISTINCT rvid FROM
(
SELECT
rvid,
#neg := rating<3, /* 0 or 1 for addition in next line */
#count := IF(#rvid <> rvid , #neg, #count+#neg) AS `count`, /* set or add */
#rvid := rvid /* remember last row */
FROM
testdb.venrate
ORDER BY
rvid, datetime desc
) subq
WHERE count>=3
;
You set a variable to a non existing id. In each chronologically sorted row you check if rating is too low, that results in 1 (too low) or 0 (ok). If rvid is not equal to the last rvid, it means a new vender section is beginning. On begin of section set the value 0 or 1, else add this value. Finally store the current row's rvid for comparison in next row process.
The code above is looking for 3 consecutive low ratings (low means a value less than 3) over all the time.
A small modification checks if all the latest 3 ratings has been equal to or less than 3:
SET #rvid = -1;
SELECT DISTINCT
rvid
FROM
(
SELECT
rvid,
#high_found := rating>3 OR (#rvid = rvid AND #high_found) unflag,
#count := IF(#rvid <> rvid , 1, #count+1) AS `count`,
#rvid := rvid /* remember last row */
FROM
testdb.venrate
ORDER BY
rvid, datetime desc
) subq
WHERE count=3 AND NOT unflag
;

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 do i get this data in the proper format?

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

Categories