Lucas
Lucas

Reputation: 3715

PHP grouping by data value

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?

Upvotes: -1

Views: 109

Answers (2)

Karoly Horvath
Karoly Horvath

Reputation: 96258

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;

Upvotes: 2

hakre
hakre

Reputation: 197658

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.

Upvotes: 3

Related Questions