删除数组的公共索引


Remove common indexes of array

我有一些索引,我需要从主数组中删除。例如:

$removeIndex=array(1,3,6);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');

我想要的最终结果是:

 $mainArray=array('2'=>'b','4'=>'d','5'=>'e');

我知道PHP中有array_slice函数,它可以循环运行,但我有非常大的数据,我想在这里避免循环

不妨试试array_diff_key:

$removeIndex=array(1,3,6);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');
$removeIndex = array_flip($removeIndex);//flip turns values into keys
echo '<pre>';
//compute diff between arr1 and arr2, based on key
//returns all elements of arr 1 that are not present in arr2
print_r(array_diff_key($mainArray, $removeIndex));
echo '</pre>';

当我尝试这个时,它返回:

<>之前的数组([2] => b[4] => d[5] => e)

您可以使用array_diff_key,请注意,在removeIndex数组中您需要将值设置为keys

$removeIndex=array('1' => 0,'3' => 0,'6' => 0);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');
$t = array_diff_key($mainArray, $removeIndex);
print_r($t);

正如@Elias指出的,您可以使用array_flip将值更改为removeIndex数组中的键。

尝试取消设置功能。这必须是完美的

unset($mainArray[1]);