1

Mysql Query:

select id, ad_click, contact_submit, MONTH(datetime) as months, YEAR(datetime) years from wpxc_leaderboard_counters order by datetime

it's showing result in this way:

Array ( 
    [0] => Array ( 
        [0] => stdClass Object ( 
            [id] => 2 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01 
        ) 
        [1] => stdClass Object ( 
            [id] => 3 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01 
        ) 
        [2] => stdClass Object ( 
            [id] => 4 [ad_click] => 1 [contact_submit] => 0 [datetime] => 2019-11-01 
        ) 
        [3] => stdClass Object ( 
            [id] => 5 [ad_click] => 0 [contact_submit] => 1 [datetime] => 2019-11-01 
        ) 
        [4] => stdClass Object ( 
            [id] => 1 [ad_click] => 3 [contact_submit] => 2 [datetime] => 2019-12-06 
        ) 
    )
)

but wanted to show in this way:

Array ( 
    [0] => Array ( 
        [11] => stdClass Object ( 
            [id] => 2 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01 
            [id] => 3 [ad_click] => 0 [contact_submit] => 0 [datetime] => 2019-11-01 
            [id] => 4 [ad_click] => 1 [contact_submit] => 0 [datetime] => 2019-11-01 
            [id] => 5 [ad_click] => 0 [contact_submit] => 1 [datetime] => 2019-11-01 
        )
        [12] => stdClass Object ( 
            [id] => 1 [ad_click] => 3 [contact_submit] => 2 [datetime] => 2019-12-06 
        ) 
    )
)

Hope this is possible with modifying array as i have used different methods and spent lots of time but nothing achieved yet.

1 Answer 1

3

You can use a substring of the date as an array key as you fetch the query results.

while ($row = $query->fetch_object()) {
    $result[substr($row->datetime, 5, 2)][] = $row;
}

The array you showed doesn't quite match your query. If you're already selecting MONTH in the query, you won't need to use substr. You can use

$result[$row->months][] = $row;

I also suggest you consider grouping by the year as well as the month for future sorting purposes, but this probably won't matter for now since your query is ordered by datetime. It depends on how you intend to use the grouped data, but if you include year as part of the key you can be sure the groups will always sort properly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your answer it helps me to build logic which was quite straight forward, I was just got stressed and unable to get the proper logic and here's what i got: $items = array(); foreach($sql as $row) { $items[$row->months][] = $row; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.