codex
codex

Reputation: 446

How to get the duplicate values in array?

 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
       )
)

"If i have array like above array that have same elements at o and 1 index but have different [liked] elements so using php i need an array like this, How could i achieve the desired result plz help"

 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
       )
)

Upvotes: 0

Views: 61

Answers (2)

codex
codex

Reputation: 446

hello guys finally i sort out the problem solution is

$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"];
            }
        }

Upvotes: 0

Ciprian Mocanu
Ciprian Mocanu

Reputation: 2206

Let's say you have your array named $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
            );
        }
    }
}

Done in just one iteration and the result will be in the $final array.

EDITED:

And if after that you want the keys not to be the id just use array_values($final)

Upvotes: 1

Related Questions