Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find array intersect for multiple values and differing key names

I have 2 arrays where they have some common id values, but the keys for these id values differ slightly.

$comps = [
  [
    'c_id' => '123',
    'status' => 'active'
  ],
  [
    'c_id' => '456',
    'status' => 'destroyed'
  ],
  [
    'c_id' => '789',
    'status' => 'active'
  ]
];

$rests = [
  [
    'r_id' => 123,
    'extra' => 'some extra info for r_id 123'
  ],
  [
    'r_id' => 456,
    'extra' => 'some extra info for r_id 456'
  ]
];

My objective here is to return all entries of the $rests array that have corresponding entries within the $comps array that have both matching ID values and a status => active.

How can one achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have seen and used array_uintersect in the past, however I can’t seem to get this to work in the desired way.

>Solution :

You can achive this with a nested foreach loop.

$matches = [];
foreach ($rests as $rest) {
    foreach ($comps as $comp) {
        if ($rest['r_id'] === $comp['c_id'] && $comp['status'] === 'active') {
            $matches[] = $rest;
        }
    }
}

print_r($matches);

Output

Array
(
    [0] => Array
        (
            [r_id] => 123
            [extra] => some extra info for r_id 123
        )

)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading