Jump to content

How to interpret cutom field


paulonline2501
 Share

Recommended Posts

hi, I've got a variable being passed to me from a third party website. in the following format "45-1," where 45 would be the item id and 1 would be the quantity. the variable could hold a few key pairs. eg: "45-1,46-3,5-3,"the first number is always the item id and the 2nd number is always the quantity. each pair separated by a comma. there is always a trailing comma. I need to deconstruct these pairs and deduct the quantity from the correct item in the products table in my database. My question is, what is the best way to deconstruct these pairs?im guessing I should put these in to an array.not totally sure how to do this. any help or ideas would be great. the variable is initially set like this:

$custom = $_POST['custom'];
Link to comment
Share on other sites

<p><?php$myString = "45-2,34-2,35-1,";echo($myString);?></p><?php$myString = trim($myString, ",");$myArray = explode(",", $myString);echo("<p>Exploded string in array:</p><ul>");foreach($myArray as $thisValue){   echo("<li>".$thisValue."</li>");}echo("</ul>");?>

I got the first explode working but struggling with the 2nd explode.

Edited by as_bold_as_love
Link to comment
Share on other sites

....actually, I think ive got it working but i'm sure there is a way to write it in a more elegant way.here's what I wrote:

<?php	$myString = trim($myString, ",");	$myArray = explode(",", $myString);	echo("<p>Exploded string in array:</p><ul>");	foreach($myArray as $thisValue)	{		$i=0;		$thisPartsValueID="";		$thisPartsValueQuantity="";		$myArrayParts = explode("-", $thisValue);		foreach($myArrayParts as $thisPartsValue)		{			if($i==0){echo("<li>id=".$thisPartsValue."</li>");$thisPartsValueID=$thisPartsValue;$i++;}			else{echo("<li>quantity=".$thisPartsValue."</li>");$thisPartsValueQuantity=$thisPartsValue;}		}		echo("insert into tableName (quantity) values (currentQuantity - $thisPartsValueQuantity) where id = $thisPartsValueID");	}	echo("</ul>");?>
Edited by as_bold_as_love
Link to comment
Share on other sites

Either of these would work:

list($id, $quantity) = explode("-", $thisValue);echo 'id = ' . $id . '<br>quantity = ' . $quantity;
$myArrayParts = explode("-", $thisValue);$id = $myArrayParts[0];$quantity = $myArrayParts[1];

The only thing I'll use foreach for is to loop through an associative array really. If you know how many items are in the array might as well just assign them directly.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...