如何将单元素关联数组的数组重组为分组的子数组? [英] How to restructure an array of single-element associative arrays into grouped subarrays?

查看:45
本文介绍了如何将单元素关联数组的数组重组为分组的子数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联数组:

Array ( 
[0] => Array ( [term_title] => black ) 
[1] => Array ( [color_quantity] => 2 ) 
[2] => Array ( [color_price] => 22 ) 
[3] => Array ( [term_title] => blue ) 
[4] => Array ( [color_quantity] => 3 ) 
[5] => Array ( [color_price] => 33 ))

如何将其更改为:

Array ( 
[0] => Array ( [term_title] => black, [color_quantity] => 2, [color_price] => 22 ) 
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

我尝试以下代码:

$post = array();
for($i = 0; $i < 2; $i++){
    foreach($feild_data as $data){
        $post[$i][$data['name']] = $data['value'];
    }
}

,但是它将最后一个索引重复两次.即

but it repeat the last index two times. i.e.

Array ( 
[0] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) 
[1] => Array ( [term_title] => blue, [color_quantity] => 3, [color_price] => 33 ) )

推荐答案

如果您喜欢语言构造和基本算术,则可以简单地遍历数组,除以3,然后将该浮点值用作第一级键-php会自动 floor()该值形成一个整数

If you like language constructs and basic arithmetic, then you can simply loop through the array, divide by 3 and use that float value as the first level key -- php will automatically floor() that value to form an integer

代码:(演示)

foreach ($array as $index => $subarray) {
    $key = key($subarray);
    $result[$index / 3][$key] = $subarray[$key];
}
var_export($result);

或者,如果您更喜欢函数语法(并且我经常这样做),则可以形成子数组组,然后合并/展平这些组.以下技术不需要声明 $ result 变量,并且可以单行编写.

Alternatively, if you prefer functional syntax (and I often do), you can form groups of subarrays, then merge/flatten the groups. The technique below does not require the declaration of a $result variable and could be written as a one-liner.

代码:(演示)

var_export(
    array_map(
        function($v) {
            return array_merge(...$v);
        },
        array_chunk($array, 3)
    )
);

两种技术都提供以下输出:

Both techniques provide the following output:

array (
  0 => 
  array (
    'term_title' => 'black',
    'color_quantity' => 2,
    'color_price' => 22,
  ),
  1 => 
  array (
    'term_title' => 'blue',
    'color_quantity' => 3,
    'color_price' => 33,
  ),
)

这篇关于如何将单元素关联数组的数组重组为分组的子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆