PHP:如何通过键对数组进行分组?

时间:2013-05-24 17:33:05

标签: php

我有一个uploads数组,如下所示:

$uploads[0] = array('type' => 'upload', 'label' => 'blah');
$uploads[1] = array('type' => 'upload', 'label' => 'blah');
$uploads[2] = array('type' => 'upload', 'label' => 'blah');
$uploads[3] = array('type' => 'upload', 'label' => 'foobar');

我想创建这个数组:

$upload_fields = array(
   'blah' => array(
               array('type' => 'upload', 'label' => 'blah')
               array('type' => 'upload', 'label' => 'blah')
               array('type' => 'upload', 'label' => 'blah')
    ),
   'foobar' => array(
               array('type' => 'upload', 'label' => 'foobar')    
    )
);

基本上我想根据标签对数组进行分组。要分组的数组是动态的,否则我可以执行以下操作:

$array_group_1 = array();
$array_group_2 = array();

foreach($uploads as $upload) {
    if($upload['label'] == 'blah') {
        array_push($array_group_1, $upload);
    }  else {
        array_push($array_group_2, $upload);        
    }
}

$upload_fields = array(
    'blah' => $array_group_1,
    'foobar' => $array_group_2
);

但是因为键是动态的,我怎么能实现这个呢?

3 个答案:

答案 0 :(得分:2)

这就是我提出的:

$uploads[0] = array('type' => 'upload', 'label' => 'blah');
$uploads[1] = array('type' => 'upload', 'label' => 'blah');
$uploads[2] = array('type' => 'upload', 'label' => 'blah');
$uploads[3] = array('type' => 'upload', 'label' => 'foobar');

foreach($uploads as $u){
    $upload_fields[$u['label']][] = $u;
}

echo '<pre>',print_r($upload_fields),'</pre>';

答案 1 :(得分:1)

您可以使用很多外来数组函数来获取动态数组键和值http://www.php.net/manual/en/ref.array.php

可以通过缩小if else语句来优化以下代码,但是我这样做是为了使示例非常清晰

$uploads[0] = array('type' => 'upload', 'label' => 'blah');
$uploads[1] = array('type' => 'upload', 'label' => 'blah');
$uploads[2] = array('type' => 'upload', 'label' => 'blah');
$uploads[3] = array('type' => 'upload', 'label' => 'foobar');

$result = array();

foreach($uploads AS $upload)
{
    if(array_key_exists($upload['label'], $result))
    {
        array_push($result[$upload['label']], $upload);
    }
    else
    {
        $result[$upload['label']] = array();
        array_push($result[$upload['label']], $upload);
    }
}

var_dump($result);

答案 2 :(得分:0)

$temp = array();
$final_array = array();

foreach($uploads as $upload){
    if(!in_array($upload['label'], $temp)){
        $final_array[$upload['label']] = array('type' => upload['type'], 'label' => $temp);
        $temp[] = $upload['label'];
    }
}

var_dump($final_array);