将数组分组到基于键/值的另一个数组中

时间:2014-11-28 08:19:56

标签: php arrays

我处于这样的情况:我希望将PHP中的数组分组到基于组ID的分组,我得到的是以下内容

Array ( 

[0] => Array ( 
[raw] => I am text string 
[group_id] => 1 
) 

[1] => Array ( 
[raw] => Another text string 
[group_id] => 1 
) 

[2] => Array ( 
[raw] => text placeholder 
[group_id] => 2 
)

) 

但我想要输出如下

Array ( 

[0] => Array ( 

Array(
[0] => Array (
[raw] => I am text string 
[group_id] => 1 
) 
[1] => Array ( 
[raw] => Another text string 
[group_id] => 1 
) 

)

[1] => Array ( 
[raw] => text placeholder 
[group_id] => 2 
)

) 

在当前输出中,您可以注意到前两个数组元素的'group_id'是相同的,即1,在预期的输出中,具有相同'group_id'的元素被包装到父数组中。

供您考虑,这是数组代码;

<?php    
$output = array(
array ("raw"=> "I am text string", "group_id" => 1), 
array ("raw"=> "Another text string", "group_id" => 1), 
array ("raw"=> "text placeholder", "group_id" => 2), 
);
print_r($output);
?>

所以最终,我想将具有相同'group_id'的数组分组到另一个数组中。

提前感谢您的时间和帮助。

任何帮助都表示赞赏,因为我没有得到逻辑。

3 个答案:

答案 0 :(得分:2)

我不认为修剪单个/单独组ID的嵌套维度有一个快捷方式,但你可以这样做:

$output = array(
    array ("raw"=> "I am text string", "group_id" => 1),
    array ("raw"=> "Another text string", "group_id" => 1),
    array ("raw"=> "text placeholder", "group_id" => 2),
);

$new = array();
foreach ($output as $value) {
    $new[$value['group_id']][] = $value;
}
// trim single/lone arrays
foreach ($new as &$value) {
    if(count($value) <= 1) {
        $value = reset($value);
    }
}

echo '<pre>';
print_r($new);

答案 1 :(得分:2)

$newArr = array();
foreach($output as $values) {
    $new[$values['group_id']][] =  $values;
}

它会为你创建数组。

答案 2 :(得分:0)

使用以下代码:

<?php    
$output = array(
array ("raw"=> "I am text string", "group_id" => 1), 
array ("raw"=> "Another text string", "group_id" => 1), 
array ("raw"=> "text placeholder", "group_id" => 2), 
);

$new = array();
foreach($output as $values) {
    $new[$values['group_id']][] =  $values;
}
$new = array_values($new);
echo '<pre>';
print_r($new);
?>