如何在PHP中合并两个具有相同ID的数组?

时间:2011-09-24 11:32:30

标签: php arrays merge

  

可能重复:
  Merge arrays (PHP)

这是我的数组如何将数组与他的'panid'合并。 相同的'panid'请参阅数组和所需的输出。

在下面的数组中显示2个数组包含相同的'panid',但它的成分是不同的。 所以我将这个2数组合并到一个数组中并合并他的成分。

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 个答案:

答案 0 :(得分: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;
}

这是完全未经测试的,但它应该会让您知道如何继续。