PHP:使用重复键重新排列数组的简单方法

时间:2014-04-11 09:09:32

标签: php arrays

我有一个像这样的数组:

0 => Array ( [invoice_id] => 376 [discount_id] => 1 [product_id] => 15 ),
1 => Array ( [invoice_id] => 376 [discount_id] => 5 [product_id] => 16 ),
2 => Array ( [invoice_id] => 376 [discount_id] => 7 [product_id] => 17 ),
3 => Array ( [invoice_id] => 254 [discount_id] => 13 [product_id] => 26 ),
4 => Array ( [invoice_id] => 254 [discount_id] => 3 [product_id] => 33 ),

我希望这个数组看起来像这样:

376 => Array (0 => Array( [discount_id] => 1 [product_id] => 15 ),
              1 => Array( [discount_id] => 5 [product_id] => 16 ),
              2 => Array( [discount_id] => 7 [product_id] => 17 )),
254 => Array (0 => Array ([discount_id] => 13 [product_id] => 26),
              1 => Array ([discount_id] => 3 [product_id] => 33))

我想知道最简单,最好,最优雅的方法是什么?

3 个答案:

答案 0 :(得分:0)

由于存在类似的键'invoice1' , 'invoice2',因此数组中的最后一个值将为'invoice1' => 'product4' and 'invoice2' => 'product3'。你将无法获得像第二个那样的数组。

答案 1 :(得分:0)

$myNewArray = array();
foreach($myBigArrayThatIWantRestructuring as $value) {
    if (!isset($myNewArray[$value['invoice_id']])) {
        $myNewArray[$value['invoice_id']] = array();
    }
    $myNewArray[$value['invoice_id']][] = array(
        'discount_id' => $value['discount_id'],
        'product_id' => $value['product_id'],
    );
}

答案 2 :(得分:0)

这是完整的例子。只需复制并粘贴:

$arrInput = array(
        0 => Array ( 'invoice_id' => 376, 'discount_id' => 1 ,'product_id' => 15 ),
        1 => Array ( 'invoice_id' => 376, 'discount_id' => 5, 'product_id' => 16 ),
        2 => Array ( 'invoice_id' => 376 ,'discount_id' => 7 ,'product_id' => 17 ),
        3 => Array ( 'invoice_id' => 254, 'discount_id' => 13, 'product_id' => 26 ),
        4 => Array ( 'invoice_id' => 254, 'discount_id' => 3 ,'product_id' => 33 ));


$res = group($arrInput, 'invoice_id');

print_r("<pre>");
print_r($res);


function group($data, $column)
{
$arrRes = array();
foreach($data as $row)
{
    if (!is_array($arrRes[$row[$column]]))
    {
        $arrRes[$row[$column]] = array();
    }
    $arrRes[$row[$column]][] = $row;
}
return $arrRes;
}