如何将多维数组中某些键的值设置为null?

时间:2017-08-19 09:26:26

标签: php arrays

我想取消设置数组值而不是键

在:

Array
(
    [0] => Array
        (
            [id] => 45
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 3000
        )
[1] => Array
        (
            [id] => 46
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 2000
        )
)

后:

Array
(
    [0] => Array
        (
            [id] => 45
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 
        )
[1] => Array
        (
            [id] => 46
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 
        )
)

4 个答案:

答案 0 :(得分:2)

我认为 数组长度 可以 增加

如下所示: -

foreach($array as &$arr){ // iterate over array
   $arr['winprize'] = ''; // empty value of desired key
}

输出: - https://eval.in/847434

答案 1 :(得分:0)

另一种方法是使用sizeof函数

for($i = 0; $i < sizeof($array); $i++) {
  $array[$i]['winprize'] = '';
}

答案 2 :(得分:0)

在循环中请留空。

e.g。

$array[0]['winprize'] = '';

答案 3 :(得分:0)

或者,您也可以使用array_map()

<?php

$data = array(
    array(
        'id' => 45,
        'type' => 1,
        'lgsize' => 10,
        'lgid' => 9,
        'rank' => 4,
        'winprize' => 3000,
    ),
    array(
        'id' => 46,
        'type' => 1,
        'lgsize' => 10,
        'lgid' => 9,
        'rank' => 4,
        'winprize' => 2000,
    ),
);

$cleaned = array_map(function (array $element) {
    // only set null as value if the key actually exists
    if (array_key_exists('winprize', $element)) {
        $element['winprize'] = null;
    }

    return $element;
}, $data);

var_dump($cleaned);

供参考,见:

有关示例,请参阅: