Jump to content

Remove Subarray from Multidimensional Array Based On Value


jmwhitaker

Recommended Posts

Hello. I am editing a plugin that is grabbing a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.

 

What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.

 

The current variable

$arrSlides

returns several subarrays that look like something like this (I remove unimportant variables for the sake of brevity):

 

Array ( 
[0] => Array ( 
[slide_active] => 1 
) 
[1] => Array ( 
[slide_active] => 0 
)
)

 

What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable

$arrSlides

.

 

I have tried a few array functions but have not had any luck. Any suggestions?

 

Thanks in advance,

Jason

Offhand, I can't think of a way to do it without looping over the array, but if the primary array indices are sequential from zero and numeric, you can use a for() loop instead of a foreach() loop. Might be a little faster.

 

$elements = count($arrSlides);
for( $i = 0; $i < $elements; $i++ ) {
     if( array_key_exists('slide_active', $arrSlides[$i]) ) {
          if( $arrSlides[$i]['slide_active'] != 1 ) {
               unset( $arrSlides[$i] );
          }
     }
}

I think array_filter() would be a better option for this:

 

function removeInactiveSlides($sub)
{
    return (!(isset($sub['slide_active']) && $sub['slide_active']===0));
}

$arrSlidesFiltered = array_filter($arrSlides, 'removeInactiveSlides');

Thanks! I wanted to avoid rewriting the 300 line foreach statement that was outputting all the variables, so I took a bit of your solution and checked to see if the key/value combo existed, unset the value if it did, then did an else for all other instances of the foreach:

 

foreach ($arrSlides as $i => $slide){
		if ($slide['slide_active'] == 0){
		unset($slide);
		}
		else {
put stuff here
}

 

Thanks for pointing me in the right direction!

 

Also, to @psycho... Your solution also worked perfectly, especially for doing the filtering prior to the foreach statement. Thanks!

 

Jason

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.