开发者

PHP grouping by data value

开发者 https://www.devze.com 2023-04-08 16:34 出处:网络
My data variable: 1开发者_如何学Python=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:

My data variable:

1开发者_如何学Python=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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消