SonDang
SonDang

Reputation: 1597

PHP match values between 2 arrays not same key

I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.

I have 2 array like below:

BigArray

Array
(
    [0] => Array
        (
            [id] => 1
            [category_name] => Accountancy
            [category_name_vi] => Kế toán
            [category_id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [category_name] => Armed forces
            [category_name_vi] => Quân đội
            [category_id] => 2
        )

    [2] => Array
        (
            [id] => 3
            [category_name] => Admin & Secretarial
            [category_name_vi] => Thư ký & Hành chính
            [category_id] => 3
        )

    [3] => Array
        (
            [id] => 4
            [category_name] => Banking & Finance
            [category_name_vi] => Tài chính & Ngân hàng
            [category_id] => 4
        )
)

and SmallArray:

Array
(
    [0] => Array
        (
            [id] => 7
            [category_id] => 2
            [jobseeker_id] => 1
        )

    [1] => Array
        (
            [id] => 8
            [category_id] => 3
            [jobseeker_id] => 1
        )
)

Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:

Matched array:

Array
    (
        [0] => Array
            (
                [2] => Armed forces                    
            )

        [1] => Array
            (
                [3] => Admin & Secretarial
            )
    )

So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(

Thanks

Upvotes: 0

Views: 44

Answers (1)

Ali Farhoudi
Ali Farhoudi

Reputation: 6020

This should do that:

foreach ($smallArray as $smallKey => $smallElement) {
    foreach ($bigArray as $bigKey => $bigElement) {
        if ($bigElement['id'] == $smallElement['category_id']) {
            $smallArray[$smallKey] = array(
                $bigElement['id'] => $bigElement['category_name'],
            );
            break; // for performance and no extra looping
        }
    }
}

After these loops, you have what you want in $smallArray.

Upvotes: 1

Related Questions