2011-09-24 56 views
-4

Possible Duplicate:
Merge arrays (PHP)如何在PHP中合併兩個具有相同ID的數組?

這是aray我的數組如何將數組與他的'panid'合併在一起。 同樣的'panid'請參閱數組和所需的輸出。

顯示下面的數組2個數組包含相同的'panid',但它的成分是不同的。 所以我會合並這兩個數組與合併他的成分。

Array 
(
    [0] => stdClass Object 
    (
     [userid] => 62 
     [panid] => 5 
     [recipeid] => 13 
     [ingredients] => 10 Kilos,1 Gram 
     [panname] => XYZ 
    ) 

    [1] => stdClass Object 
    (
     [userid] => 62 
     [panid] => 5 
     [recipeid] => 12 
     [ingredients] => 150 Gram,15 Pcs 
     [panname] => XYZ 
    ) 

    [2] => stdClass Object 
    (
     [userid] => 62 
     [panid] => 3 
     [recipeid] => 15 
     [ingredients] => 100 Gram,10 Pcs 
     [panname] => ABC 
    ) 
) 

要求輸出:

Array 
(
    [0] => stdClass Object 
    (
     [userid] => 62 
     [panid] => 5    
     [ingredients] => 10 Kilos,1 Gram,150 Gram,15 Pcs 
     [panname] => XYZ 
    ) 

    [1] => stdClass Object 
    (
     [userid] => 62 
     [panid] => 3   
     [ingredients] => 100 Gram,10 Pcs 
     [panname] => ABC 
    ) 
) 

回答

1

PHP有你可以使用這個一些偉大的數據結構類。通過擴展SplObjectStorage類來覆蓋attach方法,您可以更新您喜歡的食譜列表。你可能必須做更多的健全檢查比我所做的,但這裏有一個很簡單的例子:

class RecipeStorage extends SplObjectStorage 
{ 
    /** 
    * Attach a recipe to the stack 
    * @param object $recipe 
    * @return void 
    */ 
    public function attach(object $recipe) 
    { 
     $found = false; 
     foreach ($this as $stored => $panid) { 
      if ($recipe->panid === $panid) { 
       $found = true; 
       break; 
      } 
     } 

     // Either add new recipe or update an existing one 
     if ($found) { 
      $stored->ingredients .= ', ' . $recipe->ingredients 
     } else { 
      parent::attach($recipe, $recipe->panid); 
     } 
    } 
} 

您可以使用所有的SplObjectStorage可用的方法,也不必考慮合併添加新的食譜。

$recipeBook = new RecipeStorage; 
$recipeBook->attach($recipe1); 
$recipeBook->attach($recipe2); 

foreach ($recipeBook as $recipe => $id) { 
    echo 'Pan Name: ' . $recipe->panname; 
} 

這是完全未經測試,但它應該給你一些想法如何繼續。

+0

感謝兄弟.... – GKumar00

+0

但它拋出的錯誤: 開捕致命錯誤:傳遞給RecipeStorage參數1 ::連接()必須是對象的實例,stdClass的實例給出,堪稱/ home6/panchsof /public_html/dinnerrush/recipe.php在第63行,並在第10行的/home6/panchsof/public_html/dinnerrush/recipe.php中定義了 – GKumar00

+0

@ GKumar00我說這是未經測試的。你將不得不使它適合你的數據;我無法全程握住你的手...... – adlawson

相關問題