Devidas
Devidas

Reputation: 181

How to get unique value in array in php?

How to get unique values in multidimensional array ? We have to get only unique values in multiple array in comma seprated. check below array

Array
(
    [0] => Array
        (
            [product_id] => BAT0002
            [vendor_id] => 1,2,3,4
        )

    [1] => Array
        (
            [product_id] => BAT0003
            [vendor_id] => 3
        )

    [2] => Array
        (
            [product_id] => BAT0004
            [vendor_id] => 1,2,3
        )

)

Code:-

$vendor_id = array();
foreach ($rfq_product_master_data_array as $rfq_data_array) 
{
    $product_id = $rfq_data_array['product_id'];
    $vendor_id[] = $rfq_data_array['vendor_id'];

}
$uniquePids = array_unique($vendor_id);
echo "<PRE>";
print_r($uniquePids);

Actual result:-

Array
(
    [0] => 1,2,3,4
    [1] => 3
    [2] => 1,2,3
)

Expected result:-

Array
    (
        [0] => 1,2,3,4
    )

Upvotes: 2

Views: 197

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

you have to do below modification in foreach() and code after that:

foreach ($rfq_product_master_data_array as $rfq_data_array) 
{
    $product_id = $rfq_data_array['product_id'];

    $explodedArray = explode(',',$rfq_data_array['vendor_id']);
    foreach($explodedArray as $value){
        $vendor_id[$value] = $value;
    }
}
print_r($vendor_id); //so you can use it further directly.

//if you want comma separated string then

echo $uniquePids = implode(',',array_values($vendor_id));

Special Notes: it will give you comma separated string of all unique vendor_id in each case, like suppose if you have

Array
(
    [0] => 1,2,3,4
    [1] => 5
    [2] => 1,2,6,7
)

it will produce:- 1,2,3,4,5,6,7

Upvotes: 2

Jim.B
Jim.B

Reputation: 446

Do like this:

$vendor_ids = array();
foreach ($rfq_product_master_data_array as $rfq_data_array) 
{
    $product_id = $rfq_data_array['product_id'];
    $vendor_ids = array_merge($vendor_ids, explode(",", $rfq_data_array['vendor_id']));
}
$uniquePids = array_unique($vendor_ids);
echo "<PRE>";
print_r($uniquePids);

Upvotes: 0

Ashu
Ashu

Reputation: 1320

You can simply use built in array function:

$data = //your data array

$res1[] = implode(',',array_unique(explode(',',implode(',',array_column($data,"vendor_id")))));

//array_column : to get single column - vendor_id
//implode : to combine all vendor ids
//explode : to split ids into array
//array_unique : to get unique values
//implode : to combine unique values

Then result of all function set to $res1[] array at o index

var_dump($res1);

Expected resut in short code:

Array
(
    [0] => 1,2,3,4
)

Upvotes: 1

Related Questions