如何获取数组中的重复值?

时间:2014-12-31 08:32:46

标签: php

 Array ( 
  [0] => stdClass Object ( 
          [id] => 7 
          [quantity] => 1
          [seller_product_id] => 1419692926 
          [liked] => 16
        )
  [1]=> stdClass Object ( 
         [id] => 7 
         [quantity] => 1
         [seller_product_id] => 1419692926 
         [liked] => 20
       )
  [2]=> stdClass Object ( 
         [id] => 8 
         [quantity] => 2
         [seller_product_id] => 123 
         [liked] => 21
       )
)

"如果我有像上面的数组一样的数组,在o和1索引上有相同的元素但是有不同的[likes]元素,所以使用php我需要一个这样的数组,我怎样才能达到预期的结果plz help&# 34;

 Array ( 
  [0] => stdClass Object ( 
          [id] => 7 
          [quantity] => 1
          [seller_product_id] => 1419692926 
          [liked] => array(
                       [0]=>16
                       [1]=>20
                    )
        )

  [1]=> stdClass Object ( 
         [id] => 8 
         [quantity] => 2
         [seller_product_id] => 123 
         [liked] => 21
       )
)

2 个答案:

答案 0 :(得分:1)

我们假设您的数组名为$arr

$final = array();
foreach ($arr as $obj) {
    if (empty($final[$obj->id])) {
        $final[$obj->id] = $obj;
    } else {
        if (is_array($final[$obj->id]->liked)) {
            $final[$obj->id]->liked[] = $obj->liked;
        } else {
            $final[$obj->id]->liked = array(
                $final[$obj->id]->liked, $obj->liked
            );
        }
    }
}

仅在一次迭代中完成,结果将在$final数组中。

<强>编辑:

如果之后您希望密钥不是id,请使用array_values($final)

答案 1 :(得分:0)

你好,伙伴们最后解决了这个问题 解决方案是

$result = array();
        foreach ($productList->result_array() as $data) {
            $id = $data['id'];
            if (isset($result[$id])) {

                $result[$id]["liked"][] =$data["liked"];
            } else {
                $result[$id] = $data;
                unset($result[$id]["liked"]);
                $result[$id]["liked"][]  = $data["liked"];
            }
        }