PHP removes a sub-array from a multidimensional array by the key value of the sub-array

I have this 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) "" } } 

I want to delete all auxiliary arrays that include the value 334607943355808 in the "deleted" key in the basement. I got this code:

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

from: the PHP array deletes by value (not the key) , where it is not multicast, but how can I do this in my case?

EDIT:

I tried it like this:

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

But it does not work

+6
source share
2 answers

Just a simple foreach with reference to the helper array:

 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 } } 

Or by key in the main array:

 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 } } 

You can also retrieve deleted values, search and delete the key:

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

You can use array_map() . Try this one

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

Source: https://habr.com/ru/post/975493/


All Articles