Question

My first array is

Array (
 [0] => Array
     (
         [user_id] => 1
         [name] => name1
     )

 [1] => Array
     (
        [user_id] => 2
        [name] => name2
    )
)


My Secondarray is

Array (
 [0] => Array
     (
         [user_id] => 2
         [name] => name2
     )

 [1] => Array
     (
        [user_id] => 3
        [name] => name3
    )
)

The common array is the array with user_id=2 how to select that array ?
I want the intersection of that two arrays.

Was it helpful?

Solution

<?php
$array1 = array(
    array(
        'user_id' => 1,
        'name'    => 'foo'
     ), 
    array(
        'user_id' => 2,
        'name'    => 'foobar'
    )
);
$array2 = array(
    array(
        'user_id' => 2,
        'name'    => 'foobar'
    ), 
    array(
       'user_id' => 3,
       'name'    => 'baz'
    )
);

/**
 * Return the common sub_array of tow arrays with tow dimensions
 *
 * @param $arrayA - the first tow dimension array
 * @param $arrayB - the second tow dimension array
 *
 * @return array - an empty array in case the tow arrays don't
 * have any common elements, otherwise an tow dimension array
 * containing the common elements
 */
function get_common_array($arrayA, $arrayB) {
    $result = array();

    foreach($arrayA as $keyA=>$sub_arrayA) {
        foreach($sub_arrayA as $metadata=>$data) {
            if('user_id' === $metadata) {
                foreach($arrayB as $keyB=>$sub_arrayB){
                   if(in_array($data, $sub_arrayB)) {
                        $result[] = $sub_arrayB;
                    }
                }
            }
        } 
    }

    return $result;
}

var_dump(get_common_array($array1, $array2));

This is an workaround, but if i where you i consider changing the geometry of the tow arrays in such a way to be able to use dedicated function implemented in PHP witch are more faster then this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top