如何在多维数组中获取唯一值?我们只需要用逗号分隔多个数组中的唯一值即可。 检查下面的数组
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
)
)
代码:-
$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);
实际结果:-
Array
(
[0] => 1,2,3,4
[1] => 3
[2] => 1,2,3
)
预期结果:-
Array
(
[0] => 1,2,3,4
)
答案 0 :(得分:2)
您必须在foreach()
中进行以下修改,然后进行编码:
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));
特殊说明: :它将为您提供用逗号分隔的所有唯一vendor_id
字符串,就像假设您拥有
Array
(
[0] => 1,2,3,4
[1] => 5
[2] => 1,2,6,7
)
它将产生:-1,2,3,4,5,6,7
答案 1 :(得分:1)
您可以简单地使用内置的数组函数:
$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
然后将所有函数的结果设置为o索引处的$ res1 []数组
var_dump($res1);
预期的简短代码
Array
(
[0] => 1,2,3,4
)
答案 2 :(得分:0)
这样做:
$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);