2010-08-15 3 views
0

J'ai un tableau:PHP Grouper un tableau

Array 
(
    [customer] => One 
    [itemno] => Yellow Ribbon 
    [price] => 1,2 

) 
Array 
(
    [customer] => One 
    [itemno] => Blue Band 
    [price] => 0,5 
) 
Array 
(
    [customer] => Two 
    [itemno] => Red Tape 
    [price] => 2,0 
) 

Et je veux groupe par le client comme ceci:

Array 
(
    [One] => Array (
     [itemno] => Yellow Ribbon 
     [price] => 1,2 
     ) 
     [itemno] => Blue Band 
     [price] => 0,5 
     ) 

    [Two] => Array (
     [itemno] => Red Tape 
     [price] => 2,0 
     ) 
) 

Comment puis-je y arriver?

+0

liée à (pas un doublon de) http://stackoverflow.com/questions/3487380/php-array -push-not-the-right-function-what-to-use – VolkerK

Répondre

3

Si nous appellerons le premier départ $ array et la dernière finition $, puis:

 
$finish = array(); 
foreach ($start as $v){ 
    $finish[$v['customer']][] = array('itemno'=>$v['itemno'], 'price'=>$v['price']); 
} 
+0

Est-ce que cela produira un avertissement lorsque le reporting strict est activé? – Chris

0
$newArray =array(); 
foreach($originalArray as $item){ 
    if(!array_key_exists($item->customer, $newArray)){ 
     $newArray[$item->customer]= array(); 
    } 
    $newArray[$item->customer][] = $item; 
} 

// le résultat final sera $ newArray = array ('Customer1' => array (clients ...), '' Customer2 => array (clients ...));