开发者

Comparing Associative array and array

开发者 https://www.devze.com 2023-02-11 04:03 出处:网络
This is one array Array ( [0] => 1 [1] => 2 ) The associative array is Array ( [0] => Array ( [id_1] => 3 [id_2] =&开发者_开发问答gt; 1 ) [1] => Array ( [id_3] => 5 [id_4] =>

This is one array

  Array ( [0] => 1 [1] => 2 )

The associative array is

Array ( [0] => Array ( [id_1] => 3 [id_2] =&开发者_开发问答gt; 1 ) [1] => Array ( [id_3] => 5 [id_4] => 3 ) ) 

I want to compare these arrays and get an array containing the values that are not present in the associative array

The result should be array(3) and array(5,3)


$array1 = array(1,2);

$array2 = array(
    array(
        'id_1' => 3,
        'id_2' => 1
    ),
    array(
        'id_3' => 5,
        'id_4' => 3,
    )
);

I'm not sure if I understand the question, if you want to compare each array individually:

foreach($array2 as $subarray) {
    var_dump(array_diff($subarray, $array1));
}

returns:

array
  'id_1' => int 3
array
  'id_3' => int 5
  'id_4' => int 3

Otherwise if you don't want to loop through and flatten the array (using an array_flatten function from the php doc comments of array_values)

http://www.php.net/manual/en/function.array-values.php#97715

function array_flatten($a,$f=array()){
    if(!$a||!is_array($a))return '';
    foreach($a as $k=>$v){
        if(is_array($v))$f=array_flatten($v,$f);
        else $f[$k]=$v;
    }
    return $f;
}


var_dump(
    array_unique(
        array_diff(
            array_flatten($array2), $array1
        )
    )
);

returns:

array
  'id_1' => int 3
  'id_3' => int 5

'id_4' is not shown because it doesn't have a unique value. You can remove the keys with array_values() or leave in 'id_4' by removing the array_unique() from the code.


something like this, maybe?

$array_a = array(1, 2);
$array_b = array(array(1, 3), array(3, 1));

$result = array();

foreach($array_b as $key => $sub_array_b){
    foreach($sub_array_b as $sub_key => $value){
        if(!in_array($value, $array_a) && !in_array($value, $result)) array_push($result, $value);        
    }
}

EDIT: I typed this before you edited your question. You can still modify the code above so that it creates a different array for each subarray in your associative array.

0

精彩评论

暂无评论...
验证码 换一张
取 消