1

How to marge array result with same value, i was try array_unique but seems does not work for me

Code:

$row_content = mysql_fetch_assoc($sql); $array = unserialize($row_content['content_id']); foreach($array as $row) { print_r($row); } 

Here is result

Array ( [0] => v [1] => 2040 ) Array ( [0] => v [1] => 526 ) Array ( [0] => v [1] => 200 ) Array ( [0] => p [1] => 2040 ) Array ( [0] => p [1] => 600 ) 

Need to merge [1] or 2040 in this example, also value V or P it does not matter here

Edit:

This is what i need to get as result

Array ( [1] => 200 ) Array ( [1] => 526 ) Array ( [1] => 600 ) Array ( [1] => 2040 ) 
4
  • 3
    put your expected output? Commented Sep 7, 2018 at 15:23
  • Edited question Commented Sep 7, 2018 at 15:27
  • Please explain your use case, too, because it seems like you want to fix the sympton of a problem, instead of the problem itself. Maybe add the code that surrounds your foreach loop. Commented Sep 7, 2018 at 15:30
  • Actuely that is problem because this number is ID of post, as can you see on this screen i have duplicated posts now i.imgur.com/QWmOXYb.png Commented Sep 7, 2018 at 15:39

2 Answers 2

0

If I don't misunderstood your requirements then this is what you need.

<?php $ar1 = array(array('v',2040),array('v',526),array('v',200),array('v',2040),array('p',600)); $result = []; foreach($ar1 as $k=>$v){ $result[]=$v[1]; } $unique_v = array_unique($result); print '<pre>'; print_r($unique_v); print '</pre>'; ?> 

DEMO: https://3v4l.org/sGLlc

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm this seems to work fine,also sorting rsort($unique_v); is working fine. Thanks
0

I don't exactly get what you are trying to say. But if you want to merge/add all the values of "p" and "v". You can do it like this:

$array = array(array('v',2040),array('v',526),array('v',200),array('v',2040),array('p',600)); $keeper = array(); foreach($array as $row){ if(array_key_exists($row[0],$keeper)){ $keeper[$row[0]] += $row[1]; }else{ $keeper[$row[0]] = $row[1]; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.