2012-05-31 58 views
-3

我想在加入兩個sql表後檢索記錄。得到的陣列如下:如何將此數組轉換爲下面的數組

Array 
(
[0] => Array 
    (
     [optionId] => 150 
     [price] => 2.00 
     [name] => 1 Ice 
     [languageId] => 4 
    ) 

[1] => Array 
    (
     [optionId] => 150 
     [price] => 2.00 
     [name] => Ek Burph 
     [languageId] => 1 
    ) 

[2] => Array 
    (
     [optionId] => 151 
     [price] => 5.00 
     [name] => 2 Ice 
     [languageId] => 4 
    ) 

[3] => Array 
    (
     [optionId] => 151 
     [price] => 5.00 
     [name] => Do Burph 
     [languageId] => 1 
    ) 

) 

我想這個數組轉換成以下格式在我的應用程序易於解析。

Array 
(
[0] => Array 
    (
     [optionId] => 150 
     [price] => 2.00 
     [languages]=>array(
      [0]=>array(
       [name] => 1 Ice 
       [languageId] => 4 
      ) 
      [1]=>array(
       [name] => Ek Burph 
       [languageId] => 1 
      ) 
     ) 
    ) 

[1] => Array 
    (
     [optionId] => 151 
     [price] => 5.00 
     [languages]=>array(
      [0]=>array(
       [name] => 2 Ice 
       [languageId] => 4 
      ) 
      [1]=>array(
       [name] => Do Burph 
       [languageId] => 1 
      ) 
     ) 
    ) 

) 

即,我需要在PHP中將屬於相同optionId的項目分組,並且無法弄清楚如何。請幫忙。

+0

@RepWhoringPeeHaa我問一個問題。任何人都可以幫助我將第一個數組轉換成第二個數組? – ajaybc

+1

你是?哪裏?不,讓我的代碼不是問題。 – PeeHaa

+0

「如何將此數組轉換爲下面的數組」是問題的標題。 – ajaybc

回答

1

了它做自己:

$array2 = array(); 
    $f = 0; 
    if($array1){ 
     foreach($array1 as $option){ 
      $i = 0; 
      foreach($array2 as $option2){ 
       if($option2['optionId'] == $option['optionId']){ 
        $array2[$i]['language'][] = array('name'=>$option['name'],'languageId'=>$option['languageId']) ; 
        $f = 1; 
       } 
       $i++; 
      } 

      if(!$f){ 
       $array2[$i]['optionId'] = $option['optionId']; 
       $array2[$i]['price'] = $option['price']; 
       $array2[$i]['language'][] = array('name'=>$option['name'],'languageId'=>$option['languageId']); 
      } 

      $f = 0; 
     } 
    } 
相關問題