如何删除多个数组的某些键?

时间:2016-01-13 10:05:01

标签: php arrays

我有一个如下所示的多个数组:

$name_array = [
            ['name' => 'mike', 'number' => (int)$a],
            ['name' => 'lisa', 'number' => (int)$b],
            ['name' => 'michelle','number' => (int)$c],
];

现在我想要删除所有的'数字'是0

我尝试过这样:

 foreach ( $name_array as $key => $val )
        {
            if ( $val['number'] == 0 )
            {
                unset($name_array[$key][$val['number']]);
            }
        }

但这只是不起作用......有人可以帮我这个吗?

$ a和$ c = = 0 - 所以我想删除它们

感谢您的帮助:)

5 个答案:

答案 0 :(得分:0)

您没有覆盖相同的错误。使用此代码:

$a = 0;
$b = 200;
$c = 0;

$name_array = [
    ['name' => 'mike', 'number' => (int) $a],
    ['name' => 'lisa', 'number' => (int) $b],
    ['name' => 'michelle', 'number' => (int) $c],
];

for ($i=0; $i<count($name_array); $i++){
    if(!$name_array[$i]['number']){
        unset($name_array[$i]['number']);
    }
}
echo '<pre>';
print_R($name_array);

//示例输出

Array
(
    [0] => Array
        (
            [name] => mike
        )

    [1] => Array
        (
            [name] => lisa
            [number] => 200
        )

    [2] => Array
        (
            [name] => michelle
        )

)

答案 1 :(得分:0)

试试这段代码:

<?php 

$a = 0;
$b = 0;
$c = 10;
$name_array = [
    ['name' => 'mike', 'number' => (int) $a],
    ['name' => 'lisa', 'number' => (int) $b],
    ['name' => 'michelle', 'number' => (int) $c],
];

for ($i=0; $i<count($name_array); $i++){
    if($name_array[$i]['number']==0){
        //unset($name_array[$i]['number']);
        unset($name_array[$i]);
    }
}
echo '<pre>';
print_R($name_array);

?>

答案 2 :(得分:0)

你几乎没有你最初的努力,但访问数组的数字元素的语法是不正确的。这确实有效。

$a=0; 
$b=99;
$c=0;


$name_array = array(
    array( 'name' => 'mike',    'number' => (int)$a ),
    array( 'name' => 'lisa',    'number' => (int)$b ),
    array( 'name' => 'michelle','number' => (int)$c ),
);

foreach ( $name_array as $key => $val ) {
    if ( $val['number'] === 0 ) unset( $name_array[$key]['number'] );
}

答案 3 :(得分:0)

从数组中删除不需要的项目听起来很好用array_filter

$name_array = array_filter($name_array, function($x){
    return $x['number'] != 0;
});

答案 4 :(得分:-1)

变化

unset($key);

unset($name_array[$key]['number']);