PHP通过子数组键值从多维数组中删除子数组

时间:2014-09-18 15:46:32

标签: php multidimensional-array

我有这个阵列:

array(5) {
  [0]=>
  array(4) {
    ["nachricht"]=>
    string(9) "blablaaaa"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "18.09.2014 11:13"
    ["deleted"]=>
    string(0) ""
  }
  [1]=>
  array(4) {
    ["nachricht"]=>
    string(3) "joo"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "18.09.2014 11:56"
    ["deleted"]=>
    string(15) "334607943355808"
  }
  [2]=>
  array(4) {
    ["nachricht"]=>
    string(4) "noma"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "18.09.2014 11:56"
    ["deleted"]=>
    string(0) ""
  }
  [3]=>
  array(4) {
    ["nachricht"]=>
    string(4) "test"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "18.09.2014 11:56"
    ["deleted"]=>
    string(0) ""
  }
  [4]=>
  array(4) {
    ["nachricht"]=>
    string(4) "doh!"
    ["user"]=>
    string(15) "334607943355808"
    ["datum"]=>
    string(16) "18.09.2014 11:56"
    ["deleted"]=>
    string(0) ""
  }
}

我想删除键中包含值334607943355808的所有子数组"已删除"在子数组中。我得到了这段代码:

if(($key = array_search("334607943355808", $array)) !== false) {
            unset($array[$key]);
        }

来自:PHP array delete by value (not key),它是非多数组的,但我怎么能这样呢?

编辑:

我现在就这样试试了:

foreach($array as $delete){
      if(($key = array_search("334607943355808", $delete)) !== false) {
                unset($delete[$key]);
      }
}

但它不能正常工作

2 个答案:

答案 0 :(得分:6)

只是一个简单的foreach,带有对子数组的引用:

foreach($array as &$sub_array) {
    if($sub_array['deleted'] == '334607943355808') {
        $sub_array = null;
        break; //if there will be only one then break out of loop
    }
}

或者通过主数组中的键:

foreach($array as $key => $sub_array) {
    if($sub_array['deleted'] == '334607943355808') {
        unset($array[$key]);
        break; //if there will be only one then break out of loop
    }
}

您还可以提取deleted值,按键搜索和取消设置:

if(($key = array_search('334607943355808',
                        array_column($array, 'deleted'))) !== false) {
    unset($array[$key]);
}

答案 1 :(得分:1)

您可以使用array_map()。试试这个

$finalArr = array_map(function($v){
    if($v['deleted'] == '334607943355808') unset($v['deleted']);
    return $v;
}, $arr);