亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較 laravel 中的兩個集合數組

比較 laravel 中的兩個集合數組

PHP
HUWWW 2022-12-11 16:29:04
我正在使用laravel,我有兩個看起來像這樣的集合數組:$collection1 = [    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 800],];$collection2 = [    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 400],];所以我需要知道它們是否相同,比較兩個集合。如果在某些數組中,其中一個鍵(或多個鍵)具有不同的值,則它們將不再是相同的集合,例如在 1 個集合中,第二個項目的價格為 800,另一個集合400。有任何 laravel 集合的本機方法可以做到這一點?,或者我如何使用簡單的 php 數組來做到這一點?
查看完整描述

5 回答

?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

Laravel 集合有一個名為 diff 的方法,使用此方法您可以獲取集合中給定項目中不存在的項目。這些項目是 $collection2 ,它可以是一個數組或一個集合,所以你可以像這樣在這兩個集合之間獲取不同的項目


$collection1->diff($collection2);

它返回一個 Illuminate\Support\Enumerable 類。您可以通過調用 all() 來獲取這些項目:


$collection = collect([1, 2, 3, 4, 5]);


$differentItems = $collection->diff([2, 4, 6, 8]);


$differentItems->all();


// [1, 3, 5]

此代碼屬于 laravel 文檔。https://laravel.com/docs/7.x/collections#method-diff。最后,您可以將 $differentItems 轉換為布爾值。像這樣:


$collection = collect([1, 2, 3, 4, 5]);

$differentItems = $collection->diff([2, 4, 6, 8]);

$differentItems->isEmpty();

// return false


$collection = collect([1, 2, 3, 4, 5]);

$differentItems = $collection->diff($collection);

$differentItems->isEmpty();

// return true

更多鏈接https://laravel.com/api/7.x/Illuminate/Support/Collection.html#method_diff https://laravel.com/api/7.x/Illuminate/Support/Enumerable.html


查看完整回答
反對 回復 2022-12-11
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

遵循比較功能:


function compareCollections($c1, $c2) {

    // If the colletions have different sizes we return false:

    if (count($c1) != count($c2)) {

        return false;

    }


    // The collections have the same size, we check element by element:

    foreach($c1 as $item) {


        // We find the current element in $c1 in $c2:

        $itemToCompare = array_filter($c2, function ($compareItem) use ($item) {

            return ($compareItem['id'] == $item['id']);

        });


        // If we did not find the element in $c2, the collections are different:

        if (empty($itemToCompare)) {

            return false;

        }


        $itemToCompare = current($itemToCompare);


        // We now use PHP to check the element keys:

        $diff = array_diff_key($item, $itemToCompare);


        // If there is a different, return false:

        if (!empty($diff)) {

            return false;

        }       

    }


    // If everything is ok until here, the collections are the same:

    return true;

}

和一個測試:


$collection1 = [

    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],

    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 800],

];


$collection2 = [

    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],

    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 400],

];


$collection3 = [

    ['id' => 1, 'name'=> 'tv', 'quantity' => 1, 'price' => 1200],

    ['id' => 2, 'name'=> 'tv', 'quantity' => 3],

];


var_dump(compareCollections($collection1, $collection2)); // true

var_dump(compareCollections($collection1, $collection3)); // false


查看完整回答
反對 回復 2022-12-11
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

所以先對每個元素進行序列化,然后再進行比較。


    $serialize1 = $collection1->map(function ($item) {

        return serialize($item);

    });


    $serialize2 = $collection2->map(function ($item) {

        return serialize($item);

    });


dd($serialize1->diff($serialize2)->isEmpty());


查看完整回答
反對 回復 2022-12-11
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

據我所知,由于您的集合項是數組,因此沒有本地簡單的 Laravel 方法可以這樣做,您應該編寫一個函數來比較它們:


因此,假設您有:


$collection1 = collectt([

    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],

    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 800],

]);


$collection2 = collect([

    ['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],

    ['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 400],

]);

例如,您可以通過以下方式比較它們:


    private function collectionsAreEqual($collection1, $collection2)

    {

        if ($collection1->count() != $collection2->count()) {

            return false;

        }

        //assuming that, from each id, you don't have more that one item:

        $collection2 = $collection2->keyBy('id');

        foreach ($collection1->keyBy('id') as $id => $item) {

            if (!isset($collection2[$id])) {

                return false;

            }

            //your items in the collection are key value arrays 

            // and can compare them with == operator

            if ($collection2[$id] != $item) {

                return false;

            }

        }

        return true;

    }

    dd(collectionsAreEqual($collection1, $collection2));


查看完整回答
反對 回復 2022-12-11
?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

此方法僅在兩個集合具有相同的鍵順序時才有效。


默認情況下,Laravel 有一個 diffAssoc 方法,它實際上比較集合中的單個項目。如果要比較兩個集合數組,則必須創建自己的解決方案。


這是我創建(或者你可以說擴展)收集方法的解決方案。


首先,我映射每個項目并序列化該項目,然后對另一個集合執行相同的操作。使用 diffAssoc 方法獲取差異并對最終輸出進行反序列化。


AppServiceProvider.php


<?php


namespace App\Providers;


use Illuminate\Support\Collection;

use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider

{

    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }


    /**

     * Bootstrap any application services.

     *

     * @return void

     */

    public function boot()

    {

        Collection::macro('diffAssocMultiple', function ($anotherCollection) {

            /* @var $this Collection */

            return $this->map(function($arr) {

                return serialize($arr);

            })->diffAssoc($anotherCollection->map(function($arr) {

                return serialize($arr);

            }))->map(function($arr) {

                return unserialize($arr);

            });

        });

    }

}

用法


$diff = $collectionOne->diffAssocMultiple($collectionTwo);

請注意,此新方法返回另一個集合(基于非零)。并且它沒有 diffAssoc 所具有的“all()”方法。如果你想要一個從零開始的索引數組,那么使用 values 函數。


$diff = $collectionOne->diffAssocMultiple($collectionTwo)->values();


查看完整回答
反對 回復 2022-12-11
  • 5 回答
  • 0 關注
  • 301 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號