473,811 Members | 3,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Do I need a nested foreach loop to do this? Help...

348 Contributor
Hello everyone and happy Sunday. :)

I have a problem that I *think* I may know the solution to but have no idea how to write the code for it. I am working on a templating system wher I have created a template html file. I am using str_replace to replace the fields that I want changed. I'm not sure that I am doing this correctly either. A code sample follows.

I have a script that pulls a single customer from the database. The data that is pulled is the name of the company and other details about that company such as phone numbers, etc. Since a customer has many different phone numbers, I am getting the customer name repeated as many times as are phone numbers. This is exactly what the db should be doing but I need to somehow use php to echo the company name once and then loop all of the phone numbers, and addresses that are distinct to that customer.

Expand|Select|Wrap|Line Numbers
  1.         foreach($result as $content)
  2.         {
  3.             $out = str_replace("{LOCATION_NAME}", "$content[location_name]", "$tpl");
  4.             $out .= str_replace("{MANAGER}", "$content[manager]", "$tpl");
  5.  
  6.             $out .= str_replace("{EMPLOYEE}", "$content[employee]", "$tpl");
  7.  
  8. echo $out;
  9.         }
Of course with this foreach loop, I am getting six different pages because of my query. Should I be using two seperate queries? One to get the name of the location and then another for the multiple rows of data? I am almost sure that there is a way to maybe nest a foreach loop to get this.

Also, someone please tell me if I am doing this correctly. I created this html file and I am using fopen() to read the contents. I need to make about 7 or 8 replacements throughout that document. Is my str_replace code correct to do this? Am I on the right track here?

Would someone please help me out with this.. I really appriciate it

Frank
Aug 18 '08 #1
15 2757
fjm
348 Contributor
I have taken a break from this for a while and think I may have thought of the answer. I am thinking:

[PHP]
foreach($a as $b){
echo $b['something'];
foreach($b as $c){
echo $c['something'];
}
}
[/PHP]

Would this work? Am I on the right track?
Aug 18 '08 #2
dlite922
1,584 Recognized Expert Top Contributor
You're going about the templating the wrong way. This takes a lot of resources due to string manipulation and is absolutely not necessary.

Use Smarty templating system or another. if not, your html file should contain <?php echo $companyName ?> in it.

This way, all you have to is make sure that $companyName is a variable that's declared and initialized before you include() your html file.

for example here's an example PHP file:

[PHP]

<?php

$companyName = "test";

include("page.p hp");
exit();
?>
[/PHP]

then your page.php would include something like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. include("header.ext"); 
  3.  
  4. <div id="company"><?php echo $companyName ?></div>
  5.  
  6. include("footer.ext");
  7.  
  8.  
Hope that makes sense,



Dan
Aug 18 '08 #3
fjm
348 Contributor
Hi Dan. Thanks for the help and the direction. I used Smarty a few years back and I really didn't care for it that much. I would prefer to stay away from it where possible.

I thought about your second option of simply echoing the values in the html and I will definately go that route. That still leaves me with the same problem looping over my result set.

I need to compile one report per customer. The result set may have 5 or 10 or 20 different things associated with that customer. If I loop over the set I will get 5 or 10 or 20 reports.I only need a single report and was why I thouhgt that a nested foreach would be the ticket here.

Can you please advise? Or maybe I am not following what you were trying to say.

Thanks,

Frank
Aug 18 '08 #4
pbmods
5,821 Recognized Expert Expert
Heya, Frank.

Assuming you have a string that looks something like this:
Expand|Select|Wrap|Line Numbers
  1. <tr>
  2.   <td>{LOCATION_NAME}</td>
  3.   <td>{MANAGER}</td>
  4.   <td>{EMPLOYEE}</td>
  5. </tr>
  6.  
We'll call that $template.

You'll end up doing something like this:
Expand|Select|Wrap|Line Numbers
  1. $rendered = '';
  2.  
  3. foreach( $result as $content )
  4. {
  5.   $rendered .=
  6.     str_replace
  7.     (
  8.         array
  9.         (
  10.             '{LOCATION_NAME}'
  11.           , '{MANAGER}'
  12.           , '{EMPLOYEE}'
  13.         )
  14.       , array
  15.         (
  16.             $content['location_name']
  17.           , $content['manager']
  18.           , $content['employee']
  19.         )
  20.       , $template
  21.     );
  22. }
  23.  
This way, you render each row in the table (in this case) once for each record and then append the rendered content onto the output string.
Aug 18 '08 #5
fjm
348 Contributor
Pbmods, thanks.... I am going to try that now. I will be back soo to let you know how that worked out. Thanks soo much!

Frank
Aug 18 '08 #6
fjm
348 Contributor
Heya again Pbmods. :)

Thanks again for the help. The code you gave works and on the surface, appears to do exactly what mine was doing. It IS working, however, I still have the issue of creating 20+ reports when I only need one.

Here is the code I am currently working with:
[PHP]
<?php
require_once("d b.php");
$db = new Database('test' );

$filename = "report.tpl ";
$handle = fopen($filename , "r");
$template = fread($handle, filesize($filen ame));
fclose($handle) ;

$rendered = '';

$result = $db->Query("SELEC T location_name, addr1, city, name, email......");

foreach($result as $content)
{
$rendered .= str_replace(arr ay('{LOCATION_N AME}', '{NAME}'), array($content['location_name'], $content['name']), $template);
echo $rendered;
}
?>
[/PHP]

The foreach loops every customer with as many email addresses or phone numbers it has (whichever is more). What I need is this:

Expand|Select|Wrap|Line Numbers
  1. report1
  2. Customer1
  3. address1
  4. phone1
  5. phone2
  6. phone3
  7. phone4 ...
  8.  
  9. report2
  10. Customer2
  11. address1
  12. phone1 (maybe this customer only has 1 phone.. it should stop here and go to report 3)
  13.  
Expand|Select|Wrap|Line Numbers
  1. What I am getting is:
  2. customer1
  3. phone1
  4. customer1
  5. phone2
  6. customer1
  7. phone3
  8. customer1
  9. phone4 ...
Sorry Pbmods, I hope I am making sense here. The loop is generating massive amounts of reports instead of just a single report.

In other words, I get a new template generated for each and every phone number or employee name or whatever. I just need it all to be contained within 1 loop. It would seem to me that if I had a loop to get the customer name, address, city, state, zip and then had a second loop to get the items that customer had such as all phones, all employees, etc and compile that data with the first outer loop.

Should I be using a while loop outside and a foreach inside?
Aug 18 '08 #7
Atli
5,058 Recognized Expert Expert
Hi.

You will simply have to format the data *before* you print them, or put them into your template.

Consider this:
Expand|Select|Wrap|Line Numbers
  1. $data = array();
  2. while($row = mysql_fetch_assoc($result)) {
  3.   $data[$row['name']] = $row['number'];
  4. }
  5. foreach($data as $_name) {
  6.   $numbers = "";
  7.   foreach($_name as $_number) {
  8.     $numbers .= "<tr><td>$_number</td></tr>";
  9.   }
  10.   echo "<table><tr><th>$_name</th></tr>$numbers</table>";
  11. }
  12.  
Which would give you a table for each name, containing the numbers for that name alone.
Aug 18 '08 #8
fjm
348 Contributor
I'm sorry Atli, I wish I could say it worked. :(
Aug 18 '08 #9
pbmods
5,821 Recognized Expert Expert
Ah, ok.

The way I like to do it is to keep track of the primary key with a temporary variable:

Expand|Select|Wrap|Line Numbers
  1. $lastID = null;
  2.  
  3. foreach( $result as $content )
  4. {
  5.   if( $content['CustomerID'] != $lastID )
  6.   {
  7.     $lastID = $content['CustomerID'];
  8.     $rendered .= "<tr><th>{$content['CustomerID']}</th></tr>";
  9.   }
  10.  
  11.   $rendered .= str_replace( ... );
  12. }
  13.  
Every time you hit a new customer ID, it will add a header row.

The only gotcha here is that you have to sort your results by CustomerID first.
Aug 18 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1664
by: R Reyes | last post by:
Hi. I'm trying to make some event handlers for buttons that are nested within datalists, however I keep getting errors trying to access them and a blank page shows w/o any real error message. How can I access these nested controls correctly? For some reason I always have to use a foreach loop to search for a control within a control. Using FindControl() from the top level does not work and returns a "reference not set to an instance...
5
3128
by: =?Utf-8?B?QUEyZTcyRQ==?= | last post by:
Could someone give me a simple example of nested scope in C#, please? I've searched Google for this but have not come up with anything that makes it clear. I am looking at the ECMA guide and trying to understand Goto in this contect. PS: This is not homework.
1
1806
by: levidicom | last post by:
foreach($test as $var1){ foreach($test2 as $var2) { echo '"var1: " . $var1 . "<br>"var2: " . $var2 . "<br> \n"'; }
1
6756
by: levidicom | last post by:
foreach($test as $var1){ foreach($test2 as $var2) { echo '"var1: " . $var1 . "<br>"var2: " . $var2 . "<br> \n"'; }
1
2816
by: TSmith | last post by:
Hey Y'all, I haven't programmed in PHP in quite a while. Could anyone help me with a foreach loop in a nested array? I have a function which returns $stock (for an online pricing catalog). $stock is ( =Item, =Sale, ...) an array of column headers. $stock is ( =SL, =300, ...) an array of column headers to value for item $i
5
5247
by: Ivan S | last post by:
I'm using next snippet: $somearray = array(...); foreach($somearray as $item1) { foreach($item1 as $item2) { // ... do something ... } }
3
4489
by: numlock00 | last post by:
I have a nested 'while' loop that won't repeat, no matter how many times the outer loop repeats. The outer loop reads through an array of elements; the inner loop Ithe 'while' loop) is supposed to apply each of these elements while reading an input file. The outer loop is working fine. It will run through every element of the array. The inner loop, however, only runs once. Even though the outer loop finishes inormally, the inner loop does not...
4
2307
by: Danny Ni | last post by:
Hi, The following code snippet is causing CPU to max out on my local machine and production servers. It looks fine on Expresso though. Regex rgxVideo = new Regex(@"<embed(\s++\s*=\s*(""*""|'*'|*))*\s+src=\s*(""|')?http://www.g4tv.com/i?sv3?/(?<videokey>\d+)(""|')?(\s++\s*=\s*(""*""|'*'|*))*\s*(/\s*>|>\s*</embed>)", RegexOptions.IgnoreCase); string strBody = "<embed name=\"VideoPlayer\" src=\"http://localhost/lv3/26757\" width=\"480\"...
0
2782
by: LanaR | last post by:
Hello, one sql statement is causing severe performance issue. The problem occurs only in UDB environment, the same statemnt on the mainframe is running fine. I have an explain output from the sql. The statement itself is not that complicated, it is 3 selects and union all. Explain output is pretty big, but I could not find anything unusual. I'm new to db2 and I could be missing stuff. I am posting the explain output below and I really...
0
9730
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10651
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10392
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10403
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5555
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.