在单个数组中获取Common值

时间:2017-07-05 13:05:25

标签: php

我想在单个数组中获得常用值。下面我分享了我的代码供您参考

    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $pack = array();        
    foreach($itemsVisible as $key => $item) {
       $productid = $item->getProductId();
       $select = "SELECT `pay4later_package` FROM `pay4later_payment` where `product_id`=".$productid;
       $query = $connection->fetchall($select);           
       $pack[] = array_column($query, 'pay4later_package');                                                      
    }
    $paypack = call_user_func_array('array_merge', $pack);

输出:

$paypack = {ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%),ONIF12: 12 Months Interest Free Credit (0%)}

以上输出有两个共同的值(即)ONIF6: 6 Months Interest Free Credit (0%),ONIF6: 6 Months Interest Free Credit (0%)

如何在数组中获取这两个常用值?

2 个答案:

答案 0 :(得分:0)

  

您可以从数组中获取重复值,请查看以下示例代码..    php数组函数array_unique和array_diff_assoc用于此

$main_arr = array('test','none','abc','test','none'); //here duplicate value 
$unique_arr = array_unique($main_arr);
$duplicate_record = array_diff_assoc($main_arr, $unique_arr);//get difference 
print_r($duplicate_record);
  

检查这样的输出:

Array
(
    [1] => test
    [5] => none
)

答案 1 :(得分:0)

您可以使用array_count_values()array_filter()过滤回调。

$multiple = array_filter(
    array_count_values($paypack),
    function ($count) { return $count > 1; }
);

$paypack = array_filter(
    $paypack,
    function ($value) use ($multiple) { return isset($multiple[$value]); }
);