splitting an array without foreach
I have an array of items
$arr1 = Array(266=>"foo",178=>"bar",3="foobar");
and then I have an of array of numbers like this
$arr2 = Array(0 => 266, 1 => 178);
and so what I want to do is split array one into 开发者_如何学运维two arrays
where the values of $arr2 that match the index of $arr1 are moved to a new array so I am left with
$arr1 = Array(3="foobar");
$arr2= Array(266=>"foo",178=>"bar");
that said I know I could do this with a foreach loop but I wonder if this is a simpler and faster way to do this
something like array_diff would be could but I don't think that will work
Try:
$arr1 = array(266=>"foo",178=>"bar",3=>"foobar");
$arr2 = array(0 => 266, 1 => 178);
$tmp = array_diff_key ($arr1, array_flip($arr2));
$arr2 = array_diff($arr1,$tmp);
$arr1 = $tmp;
$arr2=array_interest($arr1,array_flip($arr2));
$arr1=array_diff($arr1, $arr2);
This should do what you want:
<?php
$arr1 = array(
266 => "foo",
178 => "bar",
3 => "foobar"
);
$arr2 = array(
0 => 266,
1 => 178
);
$foo = array_filter(
array_flip( $arr1 ),
function( $key ) use ( $arr2 ) {
return in_array( $key, $arr2 );
}
);
var_dump( array_flip( $foo ) );
The two array_flip's are there because array_filter will only take the value, not the key. Effectively, I'm not too sure whether or not this is more efficient than foreach though, you'd have to test.
精彩评论