-1

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?

3

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.

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

3 Comments

Well geez. You did the whole thing for him. How will he ever learn? ;)
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 ;)
I've learned everything already :p , because I understand the whole code, I just was having some troubles with the interpretation.
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;

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.