2014-04-11 46 views
-2

我有这样的一个数组:PHP:简单的方法来重新排列与重复键

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

我想要知道什么是最简单,最好,最优雅的方式来做到这一点?

+1

您当前拥有的数组将会是PHP中的非法数组,因为这些密钥是重复的......您真的拥有哪种数组? –

+0

是的,我很抱歉,我正在编辑它! – bbbb

回答

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; 
} 
0

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

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'], 
    ); 
}