I am in the situation where I want to group the arrays in PHP to group on the base of there group ID, What I am getting is the following

我想要在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 
)

) 

but I want the output like below

但我希望输出如下所示

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 
)

) 

In the current output, You can notice that 'group_id' of the first two array elements are the same i.e. 1, and in the expected output the elements with the same 'group_id' are wrapped into a parent array.

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

for your consideration, here is the array code;

请注意,这里是数组代码;

<?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);
?>

So ultimately, I want to group the arrays with same 'group_id' into another array.

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

Thank you in advance for your time and help.

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

any help is appreciated as I am not getting the logic.

感谢您的帮助,因为我不明白其中的逻辑。

3 个解决方案

#1


2

I don't think there is a shortcut for trimming nested dimensions for single/lone group id's but you could do something like this:

我不认为有捷径可以为单个/单个组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. MySQL / PHP:将整行推入关联数组,_without_命名每个单元格
  2. 在ajax中接收php多维数组。
  3. 查找具有特定数据字符串的数组并返回其具有的另一个数据字符串
  4. 使用PHP读取特定XML节点上特定数组的值
  5. 从数组中回显键和值
  6. Laravel将动态输入数据数组保存到数据库中
  7. 在多维数组中查找最小值并返回键
  8. 如何使用变量访问多维数组中的某些元素?
  9. 键入提示 - 指定对象数组

随机推荐

  1. 仿春雨医生 安卓app(android)
  2. 二、ANDROID命令详解
  3. android的启动过程
  4. android交叉编译工具链接下载
  5. 高级组件之进度条
  6. android 底部Tab添加水波纹效果
  7. 错误parsing XML: ubound prefix
  8. 【进阶篇】Android学习笔记――TextInput
  9. Android毕设之Fragment+TabHost(三)
  10. Android(安卓)动画之TranslateAnimation