2012-02-22 119 views
1

我有這樣的陣列分裂PHP數組由值

array 
    0 => 
    array 

     'prodid' => string '2' (length=1) 
     'qty' => int 2 
     'price' => string '100.00' (length=6) 
     'sid' => string '13' (length=2) 
    2 => 
    array 

     'prodid' => string '3' (length=1) 
     'qty' => int 1 
     'price' => string '380.00' (length=6) 
     'sid' => string '13' (length=2) 
    1 => 
    array 

     'prodid' => string '8' (length=1) 
     'qty' => int 1 
     'price' => string '300.00' (length=6) 
     'sid' => string '24' (length=2) 

如何我可以在把它分解到多維陣列,其中值「SID」匹配像這樣。

array 
    0 => 
    array 

     0 => 
     array 
      'prodid' => string '2' (length=1) 
      'qty' => int 2 
      'price' => string '100.00' (length=6) 
      'sid' => string '13' (length=2) 
     1 => 
     array 
      'prodid' => string '2' (length=1) 
      'qty' => int 2 
      'price' => string '100.00' (length=6) 
      'sid' => string '13' (length=2) 

    1 => 
    array 

     0 => 
     array 
      'prodid' => string '7' (length=1) 
      'qty' => int 1 
      'price' => string '200.00' (length=6) 
      'sid' => string '15' (length=2) 

回答

1
// $ouput array will be indexed by the 'sid' value 
$output = array(); 

// Iterate over the main array and create a new subarray if 
// it doesn't already exist, or add to it if it does. 
foreach($input as $subarr) { 
    if (!isset($output[$subarr['sid']]) { 
    // New array indexed by sid 
    $output[$subarr['sid']] = array(); 
    } 
    // Append the whole array 
    $output[$subarr['sid']][] = $subarr; 
} 

注:這會產生比你的描述略有不同的輸出,因爲它使用所述sid作爲數組鍵,而不是僅僅從0索引它們:

array 
    // Note key difference... 
    // sid == 13 
    13 => 
    array 
     0 => 
     array 
      'prodid' => string '2' (length=1) 
      'qty' => int 2 
      'price' => string '100.00' (length=6) 
      'sid' => string '13' (length=2) 
     1 => 
     array 
      'prodid' => string '2' (length=1) 
      'qty' => int 2 
      'price' => string '100.00' (length=6) 
      'sid' => string '13' (length=2) 
    // sid == 15 
    15 => 
    array 

     0 => 
     array 
      'prodid' => string '7' (length=1) 
      'qty' => int 1 
      'price' => string '200.00' (length=6) 
      'sid' => string '15' (length=2) 
2

你選擇你要組作爲新數組鍵的值和成員推到它

$new = array(); 
foreach($array as $member) 
{ 
    $key = $member['group-value']; 
    $new[$key][] = $member; 
} 

然後通過使用array_values提取新的數組裸值:

$new = array_values($new); 

就是這樣。如果你想騰出的最後一部分,你還可以創建按鍵的映射,它是你自己的數字索引:

$new = array(); 
$keys = array(); 
foreach($array as $member) 
{ 
    $key = $member['group-value']; 
    isset($keys[$key]) || $keys[$key] = count($keys);   
    $new[$keys[$key]][] = $member; 
} 
2

對於PHP5.3 +

$result = array_reduce (
    $array, 
    function ($item, $result) { 
    if (!isset($result[$item['sid']])) $result[$item['sid']] = array(); 
    $result[$item['sid']][] = $item; 
    return $result; 
    }, 
    array() 
)