Jump to content

Alternative method of creating a string from an array?


Dustin013

Recommended Posts

I am building an array from a foreach loop and then using anything foreach loop to build a string to be outputted to HTML. The code I am posting below does this, but when using inside of another script it doesn't seem to work. I am thinking there is a better method I could use when building the final string to be outputted... any suggestions?

 

<?php

$prod_id = "1234"; // Sample Product number
$img_arr = array(); // Array to place images into
$prod_data = "0001:1:100,0002:2:200,0003:1:300,0004:2:400"; // Sample string

$prod_ids = explode(",", $prod_data); // Seperate string so into PRODUCTID:QUANTITY:PRICE format
foreach($prod_ids as $value){ // Loop through each set of PRODUCTID:QUANTITY:PRICE by ,
	$prod_info = explode(":", $value);	// Seperate string yet again by : 
$img_arr[] = '<img src="https://www.yourdomain.com/sale.php?TotalCost='.$prod_info[2].'&OrderID='.$prod_id.'&ProductID='.$prod_info[0].'" width="1" height="1">';
}

// Now take all the img paths build from array, and put into a string to be outputted into HTML
foreach($img_arr as $k){
$final = $k.$final; // Could this be done differently? Maybe more effective?
}

// Output of $final (Used a textbox so you can see the output as HTML)
print '<textarea cols="120" rows="20>';
echo $final;
echo '</textarea>';


?>

Link to comment
Share on other sites

The simple way is using implode:

 

$final = implode("", $img_arr);

 

The first argument is what to put between each array item, which is nothing, aka ""

 

As for why it doesn't work inside the other script, I would need to see how you combined the scripts.

Link to comment
Share on other sites

Thanks for the tip.. got rid of the foreach loops there ;-)  Still doesn't seem to work.. I am thinking it might be the way I am building the arrays? Here is the segment of code .. its from the Interspire Shopping Cart.. I am adding the ability to track individual sales and quantities of items ordered to be passed to Post Affilliate Pro.

 

        // Include the conversion tracking code for affiliates
        foreach ($this->pendingData['orders'] as $order) {
            if (strlen(GetConfig('AffiliateConversionTrackingCode')) > 0) {
                $converted_code = GetConfig('AffiliateConversionTrackingCode');
                $converted_code = str_ireplace('%%ORDER_AMOUNT%%', $order['ordsubtotal'], $converted_code);
                $converted_code = str_ireplace('%%ORDER_ID%%', $order['orderid'], $converted_code);
                
                // Edit by Dustin to grab Product_ID
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                $query_proid = "SELECT * FROM isc_order_products WHERE orderorderid='".$order['orderid']."'";
                $result_proid = mysql_query($query_proid);
                $prod_id = ''; // Soon to be a string of product info 
                $java_arr = array(); // Java string array
                $java = ''; // Soon to be string of javascript calls
			$img = ''; // Soon to be string of img src
                
                // Setup string to look like PRODUCTID:QUANTITY:PRICE,
                while ($row_proid = mysql_fetch_array($result_proid)) {
                    if ($prod_id == '') {
                        $prod_data = $row_proid['ordprodid'].':'.$row_proid['ordprodqty'].':'.$row_proid['ordprodcost'];
                    } else {
                        $prod_data .= $row_proid['ordprodid'].':'.$row_proid['ordprodqty'].':'.$row_proid['ordprodcost'].',';
                    }
                }
                
                // Explode items seperated by,
                $prod_ids = explode(",", $prod_data);
                $prod_count = '1'; // Product Counter
                // Separate string by ,
                foreach ($prod_ids as $value) {
                    // Split apart string by : (PRODUCTID:QUANTITY:PRICE)
                    $prod_info = explode(":", $value);
                    
                    //$converted_code = str_ireplace('%%PRODUCT_ID'.$prod_count.'%%',$prod_info[0], $converted_code);
                    //$converted_code = str_ireplace('%%QUANTITY_ID'.$prod_count.'%%',$prod_info[1], $converted_code);
                    
                    // Calculate Total Price of each product ID
                    if ($prod_info[1] > '1') {
                        $price_total = $prod_info[1] * $prod_info[2]; // Price multiplied by quantity
                    } else {
                        $price_total = $prod_info[2];
                    }
                    
                    $converted_code = str_ireplace('%%PRICE_ID'.$prod_count.'%%', $price_total, $converted_code);
                    
                    // Build array of javascript commands
                    $java_arr[] = "
						<script type=\"text/javascript\">
						var sale".$prod_count." = PostAffTracker.createSale();
						sale.setTotalCost('".$price_total."');  
						sale.setOrderID('".$order['orderid']."');
						sale.setProductID('".$prod_info[0]."');
						PostAffTracker.register();
						</script>";
                    
                    $prod_count++; // Increase Product Counter by 1
                    // Img array
                    $img_arr[] = '<img src="https://www.example.com/affiliate/scripts/sale.php?TotalCost='.$price_total.'&OrderID='.$order['orderid'].'&ProductID='.$prod_info[0].'" width="1" height="1">';
                
                }
                // Image Loop - Returns $img as all img src created in foreach loop
                $img = implode("", $img_arr);

                // Build string from array created in for each loop
			$java = implode("", $java_arr);
                
                $converted_code = str_ireplace('%%JAVA%%', $java, $converted_code); // Simply Insert %%JAVA%% into affiliate tracking section of interspire
                $converted_code = str_ireplace('%%IMG_CODE%%', $img, $converted_code);
                $GLOBALS['ConversionCode'] .= $converted_code;
            }
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // End Edit
        
        }

 

Notice the part commented : // Build array of javascript commands

 

What is happening is it is not creating multiple items, only the last item in the cart... what got me thinking its not looping correctly because it is simply replacing the previous information in the array with the next item it loops through... thanks in advance for any suggestions / help :-)

Link to comment
Share on other sites

foreach ($prod_ids as $value) is the loop that is only getting the last product?  I don't see anything obviously wrong.

 

The debugging technique I would use here is printing out the values of variables at each step along the way.  You can use this for arrays:

 

print "<pre>"; var_dump($array); print "</pre>";

 

Start by printing out $prod_data after it's set.  Once you've verified that's correct, try the next step along.  Eventually you'll find a step where the input is correct but output is incorrect, and that is where the bug is.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.