使用 php 从数组中删除特定元素


Remove particular elements from an array using php

我有一个如下所示的数组

Array
    (
        [AllocationPool] => TEST do not USE
        [Quarter] => 2016-Q4
        [Segment] => Storage
        [Region] => 
        [SubRegion] => 
        [Country] => 
        [typeofrec] => 0
        [TotalAllocations] => 100
        [TotalTransfersOut] => 75
        [TotalTransfersIn] => 0
        [StartOfAllocation] => 25
        [ApprovedActivities] => 0
        [AvailableBalance] => 25
        [TotalApprovedClaims] => 0
        [Balance] => 25
        [TotalUnApprovedClaims] => 0
        [Exposure] => 25
    )

我需要从这个数组中删除一些元素并格式化为新结构。

格式化数组后,我需要更改以下结构

Array
    (
        [AllocationPool] => TEST do not USE
        [Quarter] => 2016-Q4
        [Segment] => Storage
        [Region] => 
        [SubRegion] => 
        [Country] => 
    )

php 中是否有任何方法可以使用 php 删除数组中的某些元素?

使用 unset() 取消设置数组的变量

unset($array[typeofrec]);
unset($array[TotalAllocations]);
unset($array[TotalTransfersOut]);
unset($array[TotalTransfersIn]);
unset($array[ApprovedActivities]);
unset($array[AvailableBalance]);
unset($array[TotalApprovedClaims]);
unset($array[Balance]);
unset($array[TotalUnApprovedClaims]);
unset($array[Exposure]);
如果要

从数组中删除特定元素,请使用unset((。

unset($array[typeofrec]);
unset($array[TotalAllocations]);
....

使用 array_search 获取密钥,如果找到,则将其删除,并取消设置:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]); // This will remove the element
}

以下是PHP的更多想法:如何从数组中删除特定元素?

有许多

方法可用于删除数组元素:unset()array_filterarray_reduce

一种可能的方法是:

$myArray = array_filter($myArray, function ($key) {
    return in_array($key, array('AllocationPool', 'Quarter', 'Segment', 'Region', 'SubRegion', 'Country'));
}, ARRAY_FILTER_USE_KEY);

尝试每个键

未设置( $arr["键"] (

http://php.net/manual/en/function.unset.php

假设您的数组$arr,请执行

unset( $arr["总分配"] (;

...

如果你想保留一些连续的值,你可以使用 slice((

$output = array_slice($input, 0, 6(; 保留前 6 个值

你可以看看array_filter($array, $callback, $flag) (http://php.net/manual/en/function.array-filter.php(。使用此函数,您可以从数组中过滤(删除(元素。如果仅提供数组参数,该函数将从数组中删除所有等于 FALSE 的值。如果需要,你可以提供一个回调函数来执行更复杂的过滤器,如果回调返回 false,那么给定的项目将从数组中过滤。