Search code examples
phparrayspreg-grep

Return array with all data in key


I have this array $allYearData
Now i´d like to split it into 12 parts, seperated by month.
So i use PHP preg_grep() with a foreach loop to search for data.

foreach($allYearData as $key){
    $janData[] = preg_grep("/^2015-01-.*$/", $key);
}

How can i fetch all data in each key?
As you can see in $janData i get empty keys where there is no hits. And then only the date if there is a hit.

I´d like $janData to be a new array with key 0 to contain the first hit and all data/values in that key. Like $allYearData but only with the hits from preg_grep.

$allYEarData:

Array ( 
  [0] => Array ( 
    [id] => 7811
    [objekt_element] => 23050-121-1_3105
    [objekt_nr] => 23050-121-1
    [element_nr] => 3105
    [vart] => B.Avf
    [vem] => Blå
    [anteckn] => 
    [datum] => 2015-09-29 18:00:19
  ) 
  [1] => Array ( 
    [id] => 7812
    [objekt_element] => 23050-121-1_3107
    [objekt_nr] => 23050-121-1
    [element_nr] => 3107
    [vart] => B.Avf
    [vem] => Blå
    [anteckn] =>
    [datum] => 2015-09-29 18:00:22
  )
  [2]...

$janData

Array ( 
  [0] => Array ( )
  [1] => Array ( )
  [2] => Array ( )
  [3] => Array ( )
  [4] => Array ( )
  [5] => Array (
    [datum] => 2015-01-16 04:17:01
  )
  [6] => Array ( 
    [datum] => 2015-01-16 04:16:57 
  )
  [7]

I´d like $janData to be filled

Array ( 
  [0] => Array ( 
    [id] => 7811
    [objekt_element] => 23050-121-1_3105
    [objekt_nr] => 23050-121-1
    [element_nr] => 3105
    [vart] => B.Avf
    [vem] => Blå
    [anteckn] => 
    [datum] => 2015-01-16 18:00:19
  ) 

Solution

  • $key in you foreach is array, so select where is a date you want to hit and use $key to add to result array.

    foreach($allYearData as $key){
        if (preg_grep("/^2015-01-.*$/", $key['datum']){     
            $janData[] = $key;
        }
    }