按字段将阵列中的数据分组-均匀排列

时间:2018-10-23 12:31:52

标签: php

我有带有数据的表,我想根据 type 字段对它进行平均排序,以获得这样的结果:

1 - http://site1.com
2 - http://sitex.com
3 - http://sites.com
4 - http://site2.com
5 - http://site1.com
1 - http://site2.com
2 - http://site3.com
3 - http://site6.com
4 - http://site1.com
5 - http://siteX.com
1 - http://site2.com
2 - http://site8.com
3 - http://site9.com
4 - http://site1.com
5 - http://site1.com

我想根据类型字段的值(从1-5)将数组中的混合数据分为相等的组。我要补充一点,对于 type = X 而言,数组并不总是具有相等数量的数据。有时更多,有时更少

php脚本:

<?php

$arr = array(
   array('type' => 1,'url' => 'http://site1.com'),
   array('type' => 4,'url' => 'http://site2.com'),
   array('type' => 1,'url' => 'http://site2.com'),
   array('type' => 2,'url' => 'http://sitex.com'),
   array('type' => 5,'url' => 'http://site1.com'),
   array('type' => 1,'url' => 'http://site2.com'),
   array('type' => 2,'url' => 'http://site3.com'),
   array('type' => 3,'url' => 'http://sites.com'),
   array('type' => 4,'url' => 'http://site1.com'),
   array('type' => 5,'url' => 'http://siteX.com'),
   array('type' => 3,'url' => 'http://site6.com'),
   array('type' => 4,'url' => 'http://site1.com'),
   array('type' => 5,'url' => 'http://site1.com'),
   array('type' => 2,'url' => 'http://site8.com'),
   array('type' => 3,'url' => 'http://site9.com'),
);

foreach ($arr as $a){
    echo $a['type'].' - '.$a['url'].'<br>';
}

/*-- result

1 - http://site1.com
4 - http://site2.com
1 - http://site2.com
2 - http://sitex.com
5 - http://site1.com
1 - http://site2.com
2 - http://site3.com
3 - http://sites.com
4 - http://site1.com
5 - http://siteX.com
3 - http://site6.com
4 - http://site1.com
5 - http://site1.com
2 - http://site8.com
3 - http://site9.com

--*/
?>

您知道我如何得到这样的结果吗?

2 个答案:

答案 0 :(得分:1)

像这样:

$mapped = [];

foreach ($arr as $a){
    $mapped[$a['type']][] = $a['url'];
}

答案 1 :(得分:0)

使用此代码可能对您有用。

<?php function group_by($key, $data) {
    $result = array();

    foreach($data as $val) {
    if(array_key_exists($key, $val)){
    $result[$val[$key]][] = $val;
    }else{
    $result[""][] = $val;
    }
    }
    
    return $result;
}

$arr = array(
   array('type' => 1,'url' => 'http://site1.com'),
   array('type' => 4,'url' => 'http://site2.com'),
   array('type' => 1,'url' => 'http://site2.com'),
   array('type' => 2,'url' => 'http://sitex.com'),
   array('type' => 5,'url' => 'http://site1.com'),
   array('type' => 1,'url' => 'http://site2.com'),
   array('type' => 2,'url' => 'http://site3.com'),
   array('type' => 3,'url' => 'http://sites.com'),
   array('type' => 4,'url' => 'http://site1.com'),
   array('type' => 5,'url' => 'http://siteX.com'),
   array('type' => 3,'url' => 'http://site6.com'),
   array('type' => 4,'url' => 'http://site1.com'),
   array('type' => 5,'url' => 'http://site1.com'),
   array('type' => 2,'url' => 'http://site8.com'),
   array('type' => 3,'url' => 'http://site9.com'),
);

$byGroup = group_by("type", $arr);

echo "<pre>" . var_export($byGroup, true) . "</pre>";
?>