2011-09-24 55 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

相关问题