T
T
Talyan2021-08-02 17:29:03
PHP
Talyan, 2021-08-02 17:29:03

What is the simplest way to check for an occurrence in a nested array?

Tell me please. I need to check if there is such an entry in the arr2 array whose id matches the id from the arr1 array.

$arr1=array(
0=>array('name'=>'testgroup','id'=>30),
1=>array('name'=>'testgroup2','id'=>32)
);
$arr2=array(
0=>array('name'=>'testgroup','id'=>30),
1=>array('name'=>'testgroup1','id'=>31),
2=>array('name'=>'testgroup2','id'=>32));


I only see this solution:
foreach($arr2 as $arr2item){
echo $arr2item['id']."\n";

        $matches=0;
        foreach($arr1 as $arr1item){
        if($arr1item['id']==$arr2item['id']) ++$matches;
                }

        echo "Matches: $matches\n";

}


But I think it's kind of crazy. Moreover, I'm stuck at the level of 2005, when PHP 5.3 was, and maybe some new functions have already appeared that will solve my problem somehow easier?

Meaning - Arr1 - these are the groups that the user administers, Arr2 - a list of all groups.

I need to put checkboxes in the form in front of the ARR2 items in which the condition is met (ARR1 is in ARR2)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-08-02
@rpsv

$arr1ids = array_column($arr1, 'id');
$arr2ids = array_column($arr2, 'id');
$intersecIds = array_intersect($arr1ids, $arr2ids);
$arr1inArr2 = array_filter($arr1, function(array $item) use($intersecIds) {
    return in_array($item['id'], $intersecIds);
});

Moreover, I'm stuck at the level of 2005, when PHP 5.3 was

You can see it even by the declaration of arrays :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question