合并在PHP循环中生成的数组

时间:2015-07-30 23:28:28

标签: php arrays associative-array array-merge

我有一个数组,3个在同一周内重复,但有3个不同的用户分别拥有你的总数:

@transaction.atomic
def viewfunc(request):
    # This code executes inside a transaction.
    do_stuff()

我想在一个阵列中统一一周,包括3个用户和你的总数。像这样:

array
  0 => 
    array
      'week' => '1'
      'user' => 'Oswaldo Aranha'
      'totals' => 'value'
  1 => 
    array
      'week' => '1'
      'user' => 'Protogenes'
      'totals' => 'value'
  2 => 
    array
      'week' => '1'
      'user' => 'Rego Barros'
      'totals' => 'value'
  3 => 
    array
      'week' => '2'
      'user' => 'Oswaldo Aranha'
      'totals' => 'value'
  4 => 
    array
      'week' => '2'
      'user' => 'Protogenes'
      'totals' => 'value'
  5 => 
    array
      'week' => '2'
      'user' => 'Rego Barros'
      'totals' => 'value'
  ...    

我尝试使用array 0 => array 'week' => '1' 'Oswaldo Aranha' => 'value' 'Protogenes' => 'value' 'Rego Barros' => 'value' 1 => array 'week' => '2' 'Oswaldo Aranha' => 'value' 'Protogenes' => 'value' 'Rego Barros' => 'value' 2 => array 'week' => '3' 'Oswaldo Aranha' => 'value' 'Protogenes' => 'value' 'Rego Barros' => 'value' ... array_merge()array_combine(),但没有使用array_whatever()。工作。我是怎么做到的?

3 个答案:

答案 0 :(得分:1)

您可以使用array_merge();

$arr=array_merge ( $array[0],$array[1] ,$array[3]);

我希望这会对你有所帮助:)。

了解更多信息,此链接将为您提供帮助:

http://php.net/manual/en/function.array-merge.php

答案 1 :(得分:0)

$array = [
    [
        'week' => '1',
        'user' => 'Oswaldo Aranha',
        'totals' => 'value'
    ],
    [
        'week' => '1',
        'user' => 'Protogenes',
        'totals' => 'value'
    ],
    [
        'week' => '1',
        'user' => 'Rego Barros',
        'totals' => 'value'
    ],
    [
        'week' => '2',
        'user' => 'Oswaldo Aranha',
        'totals' => 'value',
    ],
    [
        'week' => '2',
        'user' => 'Protogenes',
        'totals' => 'value'
    ]
];
function combineWeeks($array) {
    $results = [];
    for($i = 0;$i < count($array);$i++) {
        $results[$array[$i]['week']][$array[$i]['user']] = $array[$i]['totals'];
        $results[$array[$i]['week']]['week'] = $array[$i]['week'];
    }
    $combined = [];
    foreach($results as $key => $value) {
        $combined[] = $results[$key];
    }
    return $combined;
}

用法:

$combinedArray = combineWeeks($array);
print_r($combinedArray);

输出:

Array
(
    [0] => Array
        (
            [Oswaldo Aranha] => value
            [week] => 1
            [Protogenes] => value
            [Rego Barros] => value
        )

    [1] => Array
        (
            [Oswaldo Aranha] => value
            [week] => 2
            [Protogenes] => value
        )

)

答案 2 :(得分:0)

我认为没有php功能为你做这件事。只要你自己做:

$in = $array;
$out = [];
foreach ($in as $curIn) {
    if ( ! isset ($out[$curIn["week"]])) {
        $out[$curIn["week"]] = [];
    }
    $out[$curIn["week"]][$curIn["user"]] = $curIn["totals"];
}

就是这样。