0

My data variable:

1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif

I need it to be grouped by the value after =, so in this case it should look like this:

$out = array('icon_arrow.gif' => '1, 2, 3');

The 'icon_arrow.gif' field need to be unique, and can't repeat.

How it can be done?

2
  • whats the source of the original string?
    – user557846
    Sep 27, 2011 at 22:46
  • 1
    Maybe it's just me, but I completely do not understand the question. ha
    – Shackrock
    Sep 27, 2011 at 22:47

2 Answers 2

3

Initialize an array:

$array = array();

Explode the input by ,, store results as an array based on a sub-explode of it by =:

foreach(explode(',', $string) as $p)
{
   list($i, $n) = explode('=',$p);
   $array[$n][] = $i;
}

Implode then the result with ,:

foreach($array as &$v)
    $v = implode(', ', $v);
unset($v);

Done.

3
  • Well geez. You did the whole thing for him. How will he ever learn? ;)
    – webbiedave
    Sep 27, 2011 at 22:57
  • Well SO is a browser game: If you hinder users from learning from their questions, they will ask more question, you can easily answer and then you get the points ;)
    – hakre
    Sep 27, 2011 at 22:59
  • I've learned everything already :p , because I understand the whole code, I just was having some troubles with the interpretation.
    – Lucas
    Sep 27, 2011 at 23:00
2

Just for fun. With no special chars this should also work.

$str="1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif,4=x.gif";

$str = str_replace(',', '&', $str);
parse_str($str, $array);
$result = array();
foreach($array as $k=>$v)
    $result[$v] = (isset($result[$v]) ? $result[$v] . ", " : "") . $k;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.