How to work with product variations in php?
My Code to check duplicate values:
$where = "`product_id` = '$id'";
$variationsavailable = $object->getWhere('variations', $where);
foreach ($variationsavailable as $current_key => $variation)
{
foreach ($variationsavailable as $search_key => $search_variation)
{
if ($search_variation['color'] == $variation['color'])
{
if ($search_key != $current_key)
{
// echo "duplicate found: $search_key<br>";
// $newvariationsavailable=array_unique($variationsavailable[$current_key]);
// print_r($search_variation);
}
}
}
}
These are the 4 product variations ($variation) (output after first foreach loop):
Array
(
[id] => 20
[product_id] => AS_61e2c8ba1a1377.90699826398377
[variation_id] => VAR61e6b21e828584.567773554505
[size] => Medium
[color] => Yellow
[stock] => 120
[status] => 1
)
Array
(
[id] => 21
[product_id] => AS_61e2c8ba1a1377.90699826398377
[variation_id] => VAR61e6b21e82a2b2.733304005041
[size] => Small
[color] => Yellow
[stock] => 120
[status] => 1
)
Array
(
[id] => 22
[product_id] => AS_61e2c8ba1a1377.90699826398377
[variation_id] => VAR61e6b21e82ac02.349275567750
[size] => Small
[color] => White
[stock] => 120
[status] => 1
)
Array
(
[id] => 23
[product_id] => AS_61e2c8ba1a1377.90699826398377
[variation_id] => VAR61e6b21e82b483.245499117421
[size] => Large
[color] => White
[stock] => 120
[status] => 1
)
When I run the foreach loop to display size and colors
foreach ($variationsavailable as $current_key => $variation) {
echo $variation['size'];
echo $variation['color'];
}
Current Output:
SIZE: Medium, Small, Small, Large COLOR: Yellow, Yellow, White, White
How do I show duplicate values only once?
Desired Output:
SIZE: Medium, Small, Large COLOR: Yellow, White
I would create an extra array to put all the already printed out sizes and colors in.
$duplicatearray = array();
$i = 0;
foreach ($variationsavailable as $current_key => $variation) {
//Check if its the first iteration so we dont need to check if its in the
//duplicate array
if($i < 1){
echo $variation['size'];
echo $variation['color'];
duplicatearray['size'][] = $variation['size'];
duplicatearray['color'][] = $variation['color'];
$i++;
}
else{
//Check if the size is in the duplicatearray, if not then print it
if(!in_array($variation['size'], $duplicatearray['size'])){
echo $variation['size'];
duplicatearray['size'][] = $variation['size'];
}
//Check if the color is in the duplicatearray, if not then print it
if(!in_array($variation['color'], $duplicatearray['color'])){
echo $variation['color'];
duplicatearray['color'][] = $variation['color'];
}
}
}