Thread: Array Question
View Single Post
10-18-2012, 02:52 AM
#2
Village Genius is offline Village Genius
Village Genius's Avatar
Status: Geek
Join date: Apr 2006
Location: Denver, CO
Expertise: Software
Software: Chrome, Notepad++
 
Posts: 6,894
iTrader: 18 / 100%
 

Village Genius will become famous soon enough

  Old


How can I remove an array if ALL it's values are NULL?
Try something like

PHP Code:
<?php 
foreach($sorted as $a => $aKey){
    
$isNotNull=false;
    
    
//loop though each sub-array
    
foreach($a as $b){
        
// If value is not null, mark it so this part won't get deleted
        // You can save a few clock cycles by adding break here but don't,
        // the gains are minimal and break is always a bad idea. 
        
if($b != null){
            
$isNotNull=true;
        }
    }
    
    
//If nothing has marked it for saving, delete it
    
if$isNotNull=false){
        unset(
sorted[$aKey]);
    }
}

How can I merge the hr, min and sec keys into time => hr:min:sec?
This one is a tad trickier, you can expand the code above to this

PHP Code:
<?php 
foreach($sorted as $a => $aKey){
    
$isNotNull=false;
    
$isNull=false;
    
//loop though each sub-array
    
foreach($a as $b){
        
// Break isn't a good idea now. As I said before, breaking structured flow is always a bad idea. 
        
if($b != null){
            
$isNotNull=true;
        }
        else{
            
$isNull=true;
        }
    }
    
    
    
//If all values are null, delete
    
if$isNotNull=false){
        unset(
sorted[$aKey]);
    }
    
    
//If nothing is null, we might want to merge the pieces into a string
    
if($isNull==false){
        
reset($a);
        foreach(
$a as $b => $bKey){
            
$tmpArr=array();
            
$matches="";
            
//If it matches this format it might be one of the three keys we are looking for
            
if(preg_match('/^([0-9]+)-([A-z]+)-([0-9]+)$/',$bKey,$matches) !== false){
                
//If it is an hour element
                
if($matches[1]=="hr")
                    
$tmpArr[0]=$b;
                    
                
//If it is a minute element
                
if($matches[1]=="min")
                    
$tmpArr[1]=$b;
                    
                
//If it is a seconds element 
                
if($matches[1]=="sec")
                    
$tmpArr[2]=$b;
            }
            
            
//If the array has a size of 3, it means we found the necessary pieces to have the string
            
if(sizeof($tmpArr==3)){
            
$a[$aKey]["timestring"]=$tmpArr[0] . ':' $tmpArr[1] . ':' $tmpArr[2];
            }
        }
    }
}
I haven't ran this so it might have parse errors and such but the algorithm should work.