Jump to content

Create SKU (Stock Keeping Unit) using PHP


thara

Recommended Posts

I need to create the unique SKU (Stock Keeping Unit) name for each products mixed with
product.id,product.name,product.category and product.brand. There is no problem to do it,

i.e.: SKU for a product with

id=13,
name=Bio Clean green and
category=INSECTS KILLERS
brand=HARPIC

becomes : BI-IKHA0013

This is how I tried:

$inm = "Bio Clean green500ml";
$cnm = "INSECTS KILLERS";
$bnm = "HARPIC ";

echo SKU_gen($inm, $cnm,$bnm,20).'<br>';


function SKU_gen($pname, $cat=null, $brand=null, $id = null, $l = 2){
    $results = ''; // empty string

    $str1 = array_shift(explode(' ',$pname));
    $str1 = strtoupper(substr($str1, 0, $l));

    $str2 = array_shift(explode(' ',$cat));
    $str2 = strtoupper(substr($str2, 0, $l));

    $str3 = array_shift(explode(' ',$brand));
    $str3 = strtoupper(substr($str3, 0, $l));

    $id = str_pad($id , 4, 0, STR_PAD_LEFT);

    $results .= "{$str1}-{$str2}{$str3}{$id}";
    return $results;
}

But this function is not working as expected when category of brand values become NULL.

Link to comment
Share on other sites

This is my take on things and it does throw an error is an input is null:

<?php
$inm = "Bio Clean green500ml"; 
$cnm = "INSECTS KILLERS";
$bnm = "HARPIC ";

echo SKU_gen($inm, $cnm,$bnm,20).'<br>'; 
function SKU_gen($pname, $cat=null, $brand=null, $id = null, $l = 2){
	if($pname == null) echo "empty<br><br><br>";
	
	$result = "";
	if($pname == "Bio Clean green500ml"){
		$result = "BI-";
	}
	else{
		$result = "XX-";
	}
	
	if($cat == "INSECTS KILLERS"){
		$result = $result."IK";
	}
	else{
		$result = $result."XX";
	}
	
	if($brand == "HARPIC "){
		$result = $result."HA";
	}
	else{
		$result = $result."XX";
	}
	
	$num = 10000 + $l;
	$result = $result.substr($num,1);
	
	if (strpos($result, "XX") !== false){
		echo "There is an error: ".$result;
	}else{
		echo $result;
	}
}
?>   

with a lot of products I'd use switch statements instead of the if then statements.

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.