Home > front end >  Eliminate duplicates in a foreach
Eliminate duplicates in a foreach

Time:06-05

I'm doing a query to the database and it returns an array like this to me

Array
(
    [0] => Array
        (
            [product_id] => 1460
            [productCode] => 8011
            [colorCode] => 5
            [productName] => cottonCloth
            [productInventory] => 8763
            [productSize] => 8080
            [degree] => A
            [productType] => 3
        )

    [1] => Array
        (
            [product_id] => 1461
            [productCode] => 8011
            [colorCode] => 5
            [productName] => cottonCloth
            [productInventory] => 3064
            [productSize] => 8080
            [degree] => B
            [productType] => 3
        )

    [2] => Array
        (
            [product_id] => 1462
            [productCode] => 8011
            [colorCode] => 5
            [productName] => cottonCloth
            [productInventory] => 323
            [productSize] => 8080
            [degree] => C
            [productType] => 3
        )

    [3] => Array
        (
            [product_id] => 1463
            [productCode] => 8011
            [colorCode] => 5
            [productName] => cottonCloth
            [productInventory] => 161
            [productSize] => 8080
            [degree] => 5
            [productType] => 3
        )

)

In this array, the productCode, colorCode, productName, productSize are the same, but the degree is different. When I write foreach ColorCode or ProductSize is displayed, if I want to show only one of them when it is duplicate, it shows me all those duplicates.

<select >
<? foreach($data['info'] as $size)  { ?>
<option><?=$size['productSize']?></option>
<? } ?>

CodePudding user response:

This is how you get the unique value of a specific row from the multidimensional array.

    $sizes= array_column($data['info'], 'productSize');
    $uniqueSizes = array_unique($sizes);
    
    <select >
    <? foreach($uniqueSizes  as $size)  { ?>
    <option><?=$size?></option>
    <? } ?>

CodePudding user response:

<select >
<? foreach($data['info'] as $size => $value)  { ?>
<option><?=$value->productSize?></option>
<? } ?>

Try This

  •  Tags:  
  • php
  • Related