Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looping through an array of data - how would you skin this cat 1

Status
Not open for further replies.

codequirks

Programmer
Nov 18, 2008
11
GB
Hi folks

Just looking for some advice as to what is the most efficient way to do the following, there are several ways but some expertise on efficiency would be great!? Thanks for advice in advance!

There is a MySQL table which contains 'Products' which is outside of my control. There are queries which return either ALL of the 'products' or 'products of a certain type - i.e Select * where type ='fruit'.

What I need to do is print an inventory of these to the screen but separated into 'types' so the user sees a header saying FRUITS then all the fruits, then VEGETABLES and all the veg etc. So what is the best way to do this, multiple calls to the DB and then just echo out each array or just get the one big array (the inventory isn't that big - about 100 items) and somehow (how?) loop through these?

Thanks and hope you are all having a lazy Saturday!
 
Use the mysql_query() function to run your own query on the DB to get a recordset that is already sorted:
Code:
Res = mysql_query("SELECT Products.* FROM Products ORDER BY Products.type;");
arr = mysql_fetch_array(Res);

check out this link to php's documentation for more info:

 
can you share the functions that query the database? or can you use your own sql? if so then the code below can be simplified (you can cut out one loop)

Code:
<?php
$records = selectAllRecords();
$_records = array();

foreach($records as $record):
	$type = $record['type'];
	$_records[$type][] = $record;
endforeach;

//sort by key
ksort ( $_records, SORT_REGULAR);
$_type = '';
foreach($_records as $type => $records):
	if($type !== $_type):
		echo '<h1>'.htmlspecialchars($type) . '</h1>';
		$_type = $type;
	endif;
	foreach ($records as $record):
		echo '<pre>' . print_r($record, true) . '</pre>';
	endforeach;
endforeach;
?>

 
You should really look into a PHP framework... it will make your life much easier.. it makes database management stuff super easy... look on youtube for examples... I would recommend CodeIgniter, DooPHP or CakePHP... CakePHP is the slowest out of those two...

CodeIgniter has probably the best documentation... much better than DooPHP...




Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top