How to restructure an array of single-element associative arrays into grouped subarrays?

Deadly 提交于 2021-01-29 03:00:01

问题


I have an associative array:

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

How can I change it into:

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

I try the following code:

$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 ) )

回答1:


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

Code: (Demo)

foreach ($array as $index => $subarray) {
    $key = key($subarray);
    $result[$index / 3][$key] = $subarray[$key];
}
var_export($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.

Code: (Demo)

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,
  ),
)



回答2:


Not sure from where name and value came in $data['name'] and $data['value'], but you can use array_chunk to divide them in chunks and assign them to $posts.

<?php

$posts = array();
foreach(array_chunk($field_data,3) as $data){
    $temp = [];
    foreach($data as $field){
        foreach($field as $key => $value){
            $temp[$key] = $value;
        }
    }

    $posts[] = $temp;
}


print_r($posts);


来源:https://stackoverflow.com/questions/62098442/how-to-restructure-an-array-of-single-element-associative-arrays-into-grouped-su

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!