简体   繁体   中英

PHP how to remove key from multidimensional array?

I want to remove key 1 from PHP array. I know how to achieve this by using foreach loop but i want array_filter solution. Anyone know How can I achieve this by using array filter method?

PHP Array:

Array (
    [0] => Array
        (
            [0] => 5000
            [1] => 25
            [2] => 44
        )

    [1] => Array
        (
            [0] => 5000
            [1] => 25
            [2] => 48
        )

    [2] => Array
        (
            [0] => 5000
            [1] => 26
            [2] => 44
        )

    [3] => Array
        (
            [0] => 5000
            [1] => 26
            [2] => 48
        )

)

Expected result:

Array
(
    [0] => Array
        (
            [0] => 5000
            [1] => 44
        )

    [1] => Array
        (
            [0] => 5000
            [1] => 48
        )

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

    [3] => Array
        (
            [0] => 5000
            [1] => 48
        )

)

You can't use array_filter() for this purpose. Use array_reduce() instead

$newArr = array_reduce($array, function($carry, $item){
    $carry[] = [$item[0], $item[2]];
    return $carry;
});

Check result in demo

You can't use array_filter for this. array_filter processes the values, but you want to remove a specific key.

Use array_splice() to remove an index and have all following increments adjust.

foreach ($array as &$element) {
    array_splice($element, 1, 1);
}

The & makes this a reference variable, so modifying the variable affects the elements in the array.

If processing an array of indexed arrays, @Barmar's iterated array_splice() calls are ideal because they re-index the subarrays after the targeted key is removed. Here is a functional and dynamic variation on his answer.

( Both Demos )

$array = [
    [5000, 25, 44],
    [5000, 25, 48],
    [5000, 26, 44],
    [5000, 26, 48],
];

$omitKey = 1;

var_export(
    array_map(
        function($row) use($omitKey) {
            array_splice($row, $omitKey, 1);
            return $row;
        },
        $array
    )
);

If you have an array of associative arrays (not indexed), then array_splice() is not the correct tool because it relies on positions, not keys. Use unset() instead.

$array = [
    ['a' => 5000, 'b' => 25, 'c' => 44],
    ['a' => 5000, 'b' => 25, 'c' => 48],
    ['a' => 5000, 'b' => 26, 'c' => 44],
    ['a' => 5000, 'b' => 26, 'c' => 48],
];

$omitKey = 'b';

var_export(
    array_map(
        function($row) use($omitKey) {
            unset($row[$omitKey]);
            return $row;
        },
        $array
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM