在key/value的基础上将数组分组到另一个数组中
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);
更多相关文章
- MySQL / PHP:将整行推入关联数组,_without_命名每个单元格
- 在ajax中接收php多维数组。
- 查找具有特定数据字符串的数组并返回其具有的另一个数据字符串
- 使用PHP读取特定XML节点上特定数组的值
- 从数组中回显键和值
- Laravel将动态输入数据数组保存到数据库中
- 在多维数组中查找最小值并返回键
- 如何使用变量访问多维数组中的某些元素?
- 键入提示 - 指定对象数组