Page 1 of 1

foreach nested loops (complete newb Q)

Posted: Tue Sep 13, 2011 2:28 am
by newToThis
Hi, I'm extremely new to this.
I've got an array of product codes with values of some numeric qty i.e.
prodCode: 6722 QTY: 1
prodCode: 6724 QTY: 1

This is array is obtained via POST from an order form (and it works, meaning I can echo the array).

I want to link the product codes to their descriptions so I can ech the order form back to the client.
The descriptions are in a text doc in the form: prodcode description
i.e. 6722 Hydrocolloid Blister Care
6724 Toe Spreader

This also seems to work, meaning I can create an array of lines of text from the document, which i can echo on screen.

pseudo code:

foreach order form_prodCode
foreach products_List_prodCode
if form_prodCode is the same as products_List_prodCode then
echo code, description and qty
break
(end if)
(end foreach loop)
(end foreach loop)

Unfortunately i can't get it to work, if i remove the break statement below strpos seems to find the code string just about everywhere. With the break it finds two occurences (as it should) but it displays the wrong products and the strpos doesn't make anysense to me at all.

I get the following output everytime for
$pos, $code, $desc, QTy:

0, 6722, BP1240 BP ANKLE STEP IN SMALL, QTY: 2
27, 6724, 6136 1.2.3 PREMIUM FIRST AID LARGE, QTY: 1

Actual code:

Code: Select all

$data = file_get_contents("prodDB.txt"); //read the file
	$lineOfData = explode("\n", $data); //create array separate by new line

	foreach($allCodes as $code => $num)
	{
	foreach($lineOfData as $desc)
	{
	$pos = strpos($desc, $code);
        if ($pos === false) 
	{
	//prod code not in desc, do nothing
	} 
	else 
	{
	echo "$pos, $code, $desc, QTY: $num <br />";
	break;
	}
	}
	}
?>

Apologies if it's really basic, I'm trying to teach myself PHP from the manual.
Steve

Re: foreach nested loops (complete newb Q)

Posted: Tue Sep 13, 2011 4:03 am
by twinedev
I could not figure out your exact intent of the first number for output ($pos), but other than that, here is something that should work:

Code: Select all

<?php

	// Your existing code that gets POST to the array
	// The line below simulates it for testing...
	$aryOrder = array(
		array('prodCode'=>6722,'QTY'=>1),
		array('prodCode'=>6724,'QTY'=>1),
		array('prodCode'=>8872,'QTY'=>3)
	);



	$aryFile = file('prodDB.txt'); // read file into an array

	$aryData = array();

	foreach($aryFile as $strLine) {
		if (preg_match('/^([a-z0-9]+)\s(.+)$/i',$strLine,$regs)) {

			// If the line matched good (  PROD_CODE PROD_DESC ) then
			// $regs[1] will be the Prod Code and
			// $regs[2] will be the Prod Description

			$regs[2] = trim($regs[2]);
			if ($regs[2]=='') {
				$aryData[$regs[1]] = '(NO DESCRIPTION)';
			}
			else {
				$aryData[$regs[1]] = $regs[2];
			}
		}
	}

	// We now have data from the form in $aryOrder and
	// data from the text file in $aryData

	foreach($aryOrder as $aryItem) {
		if (array_key_exists($aryItem['prodCode'],$aryData)) {

			// NOT SURE WHAT $pos IS SUPPOSED TO BE??
			
			echo $pos, ', ', $aryItem['prodCode'], ', ', $aryData[$aryItem['prodCode']], ' QTY: ', $aryItem['QTY'], "<br />\n"; 
		}
	}

?>

Re: foreach nested loops (complete newb Q)

Posted: Tue Sep 13, 2011 7:01 pm
by newToThis
Thanks twinedev,
I can't get your solution to work though--entirely my fault, I'm sure.
I still don't know why strpos didn't work, clearly I don't understand how it works (BTW I only included the $pos in the readout to try and see why it wasn't working as I thought it should).
No matter.
I see from your reply that preg_match is the way to go. Mind you, I can't see how what you've supplied fits with the description in the manual i.e. preg_match ( $stringToSearch , $stringToFind).
Anyway, I may have mislead with my description of my input arrays.
The order form post array is actually:

prodCode[6722] with a value of (for instance) 2
prodCode[6724] with a value of (for instance) 1

It's obtained from boxes on the order form (I've altered my code to use your variable names) thus:

Code: Select all

$aryOrder = $_POST['prodCode'];
I've noticed that products that aren't ordered (no value in the box) aren't present in the posted array.

The list of product descriptions in prodDB.txt is as previously described i.e.
6722 Hydrocolloid Blister Care
6724 Toe Spreader
And so on...

I changed your code in two places:

Code: Select all

foreach($aryOrder as $aryItem => $qty) {
And...

Code: Select all

echo $aryItem['prodCode'], ', ', $aryData[$aryItem['prodCode']], ' QTY: ', $qty, "<br />\n";
Thinking that would work, but it doesn't.

What am I doing wrong?
Steve

Re: foreach nested loops (complete newb Q)

Posted: Tue Sep 13, 2011 7:05 pm
by twinedev
Heading out for some sushi, will look at this when I get home later.

Re: foreach nested loops (complete newb Q)

Posted: Wed Sep 14, 2011 4:51 pm
by newToThis
Hi, preg_match isn't working the way I feel it should.

$aryOrder:
prodCode[6722] with a value of (for instance) 2
prodCode[6724] with a value of (for instance) 1
etc

prodDB.txt
6722 Hydrocolloid Blister Care
6724 Toe Spreader
etc

I get an echo with no matches for any ordered product i.e.
no match: 6724, 6724 CARNATION TOE SPREADER
when clearly, the product code (6724 $aryItem) is present in the text file line ($line_of_text).

I just don't get it!

Code: Select all

foreach($aryOrder as $aryItem => $qty) {
	  $file_handle = fopen("prodDB.txt", "r");
	  while (!feof($file_handle)) {
	   $line_of_text = fgets($file_handle);
	   if (preg_match($aryItem, $line_of_text))
	     {
	      echo "Matched! $aryItem, $line_of_text QTY: $qty <br>";
 	     }
 	   else
 	    {
 	   echo "no match: $aryItem, $line_of_text <br>";
	    } 
	    }
	   fclose($file_handle);					
       }
 
Steve

Re: foreach nested loops (complete newb Q)

Posted: Thu Sep 15, 2011 12:19 am
by newToThis
Thanks again for your help twinedev.

My problem has been solved (not by me)

Code: Select all

$products = file('http://url/prod.txt');
was a turning point.

The final script used:

Code: Select all

if( ($split = strpos($product,' ')) === FALSE ) {
		// No space found, so report it 
		echo 'Error trying to parse line '.($line+1).' ('.$product.')<br>';
		// And skip the rest of the code for this line
		continue;
	}
	// Split the string based on where the space is.
	$id = substr($product,0,$split);
	$name = substr($product,$split+1);
	// Populate the formatted array
	$products[$id] = $name;
}
// Destroy the raw array because we don't need it anymore
unset($products_raw);

// Loop through orders
foreach( $orders as $item => $quantity ) {
	// Now we don't have to use array_search, which is a slow function, especially when
	// dealing with big arrays
	if( isset($products[$item]) ) {
		echo 'Matched! You want '.$quantity.' of '.$products[$item];
	} else {
		echo 'Could not match '.$item;
	}
	echo '<br>';
}
Steve

Re: foreach nested loops (complete newb Q)

Posted: Fri Sep 16, 2011 1:12 am
by twinedev
Sorry, I had issues come up that side tracked me that were quite important, that and being up for several days with just about 2-3 hours sleep each day caught up with me...

Glad to hear you got it working.

-Greg