Search code examples
laravelapilumen

two json data are the same, no need to display


here I have two json data, in the json data in model1 judul_kontrak and model2 nama_proyek there are two the same data aa, aa and cc data in model2 do not need to be displayed, only model1 data is displayed which are not the same.

the exit should only be bb from model1

$model1 = [
    [
        'judul_kontrak' => 'aa',
        'kode' => '01'
    ],
    [
        'judul_kontrak' => 'bb',
        'kode' => '02'
    ]
];
$model2 = [
    [
        'nama_proyek' => 'aa',
        'kode' => '05'
    ],
    [
        'nama_proyek' => 'cc',
        'kode' => '06'
    ]
];
$arr = [];
$proyek = [];
foreach ($model1 as $m1) {
    $proyek['nama_proyek'] = $m1['judul_kontrak'];
    foreach($model2 as $m2){
        if(trim(strtolower($m1['judul_kontrak'])) == trim(strtolower($m2['nama_proyek']))){
            $proyek = [];
        }
    }
    $arr[] = $proyek;
}
return $arr;

Solution

  • you can use laravel collect() function

    $model1 = [
        [
            'judul_kontrak' => 'aa',
            'kode' => '01'
        ],
        [
            'judul_kontrak' => 'bb',
            'kode' => '02'
        ]
    ];
    $model2 = collect([
        [
            'nama_proyek' => 'aa',
            'kode' => '05'
        ],
        [
            'nama_proyek' => 'cc',
            'kode' => '06'
        ]
    ]);
    $arr = [];
            
    foreach ($model1 as $item) {
        $val = $item['judul_kontrak'];
        $check = $model2->where('nama_proyek', $val)->count();
        if (!$check) {
            $arr[] = $item;
        }
    }
    return $arr;
    

    it result is

    [{
        "judul_kontrak": "bb",
        "kode": "02"
    }]
    

    it only return $model1 data which is not present in model2's nama_proyek