1

I want to check, if array A contains all the items from array B (may contain others, but must contain all), when both arrays are multidimensional, i.e. can contains different variable types.

I've seen a lot (particularly this, this, this, this, this and this, also this, this and this as well). I've read PHP doc. Everything, that I checked, fails with "Array to string conversion" notice. Especially wen using array_intersect() or array_diff().

I'm using strict error checking, so notices actually holds further execution of entire script and are something, I don't generally like and want to avoid. Is it possible in this case?

My array A is:

Array
(
    [0] => content/manage/index
    [Content] => Array
        (
            [title] => 
            [type] => 5
            [category] => 
            [recommended] => 
            [featured] => 
            [status] => 
            [views] => 
            [last_access_date] => 
            [creation_date] => 
            [modification_date] => 
            [availability_date] => 
            [author_id] => 
        )

)

My array B is:

Array
(
    [0] => /content/manage/index
    [Content] => Array
        (
            [type] => 1
        )

)

So, is there any way I can if I can use array_intersect on multidimensional arrays containing different variable types without getting notice?

Community
  • 1
  • 1
trejder
  • 17,148
  • 27
  • 124
  • 216

1 Answers1

0

My problem (and question) came out of misunderstanding, what "Array to string conversion" notice really means. In my case, it was trying to tell me, that I'm trying to walk multidimensional array with functions designed to be used on single dimension array.

Understanding that led me to a solution within few seconds. There are many of them here, on SO, but the one given by deceze here looked the best for me. So I adopted it into the form of such function:

function recursiveArrayIntersect($array1, $array2)
{
    $array1 = array_intersect_key($array1, $array2);

    foreach($array1 as $key=>&$value)
    {
        if(is_array($value)) $value = recursiveArrayIntersect($value, $array2[$key]);
    }

    return $array1;
}

I adopted it to my project and my way of coding, but all the credits still goes to deceze (his answer here)!

Now I can find an intersection of virtually any array, no matter what kind of variable types it contain and no matter of, how deep it is (how many subarrays it contains).

Community
  • 1
  • 1
trejder
  • 17,148
  • 27
  • 124
  • 216