开发者

How to merge two arrays with same id in PHP? [duplicate]

开发者 https://www.devze.com 2023-04-07 11:00 出处:网络
This question already has answers here: Closed 11 yea开发者_C百科rs ago. Possible Duplicate: Merge arrays (PHP)
This question already has answers here: Closed 11 yea开发者_C百科rs ago.

Possible Duplicate:

Merge arrays (PHP)

This is aray my array how i merge array with his 'panid'. same 'panid' please see array and required output.

show below array the 2 array contain same 'panid' but it's ingredient are different. so i will merge this 2 array in one array with merge his ingredient.

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
    )
)

Require Output :

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
    )
)


PHP has some great datastructure classes you can use for this. Extending the SplObjectStorage class to override the attach method, you can update your list of recipes however you like. You will likely have to do more sanity checking than I've done, but here's a fairly simple example:

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);
        }
    }
}

You can use all of the methods available in SplObjectStorage and add new recipes without having to think about merges.

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

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

This is completely untested, but it should give you some idea how to proceed.

0

精彩评论

暂无评论...
验证码 换一张
取 消