-2

I have a mySQL query to fetch data from a whole year: $allYearData = $stmt->fetchAll();
Now i´d like to split this array into 12 parts, separated by month.

UPDATE
So i count rows in $allYearData:

//Count all keys
$allYearDataCount = Count($allYearData);

Now i use PHP preg_grep() to search and put result in new array $janData.

for($i = 0; $i <= $allYearDataCount; $i++){
    $janData[] = preg_grep("/^2015-01-.*$/", $allYearData[$i]);
}

Result:
preg_grep() expects parameter 2 to be array, null given

If i check $allYearData for data i can see it´s full.

$allYearData = $stmt->fetchAll();
print_r($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....

What am i doing wrong?

Björn C
  • 3,860
  • 10
  • 46
  • 85
  • Are you sure that you are calling `$allYearData = $stmt->fetchAll();` before iterating over `$allYearData` using the `for` loop? – mario.van.zadel Oct 14 '15 at 07:01

3 Answers3

1
for($i = 0; $i <= $allYearData; $i++){
    $janData[] = preg_grep("/^2015-01-.*$/", $allYearData[$i]);
}

First, you have $i <= $allYearData, so allYearData is number, or array? With loop there should be an integer there. Use count($allYearData) instead. and not <= but <.

Second, use foreach loop, so you will have no problem with counting items. Or think twice before using for.

Daimos
  • 1,473
  • 10
  • 28
  • I updated my question with `count`. Also i removed `=`. Now the loop runs smoothly. Thank you. I will also have a look at `foreach`. Now i have a new problem. `$janData` contains same values as `allYearData` .. The filter loop don´t work... – Björn C Oct 14 '15 at 07:13
  • 1
    - is a special char inside regexp, so instead of /^2015-01-.*$/, try to use: /^2015\-01\-.*$/ – Daimos Oct 14 '15 at 08:18
1

You have to change

for($i = 0; $i <= $allYearData; $i++){

to

for($i = 0; $i < $allYearData; $i++){

because your array starts at index 0 and will end with index count($allYearData)-1.

In your code you are accessing the array with an index out of bounds so that $allYearData[$i] will be null in the last iteration of your for loop.

mario.van.zadel
  • 2,919
  • 14
  • 23
1

In this Code $allYearData[$i] must be array. If you will have a look for error preg_grep() expects parameter 2 to be array, null given that 2 parameter needed and you have given but last parameter is not array and its required so its assume null last parameter. You will have to check your loop and make sure second parameter is Array data type

for($i = 0; $i < $allYearData; $i++){
    $janData[] = preg_grep("/^2015-01-.*$/", $allYearData[$i]);
}
Sateesh
  • 1,327
  • 9
  • 12