William William - 5 months ago 11
PHP Question

How may I create this array in PHP?

I have a query from database that returns an array of values and puts into

$history array
.
Each value have the
course_id
,
unit_id
and the
time_stamp
.

I'd like to have another array with the
course_id
and the respective
unit_ids
.

The
course_id
has to have the latest
time_stamp
and each
unit_id
has to have it's own
time_stamp
.

It's also needed to have max 4 units in each course
array
.

(Luckly the
$history
array from DB is already
ORDER BY time_stamp DESC
so I guess I only need to get the first
time_stamp
for the course and the first 4 units of each course).

So what I need is:

courseListArray:
array[0]:
course_id: closest time_stamp
unit_id: time_stamp
unit_id: time_stamp
unit_id: time_stamp
unit_id: time_stamp
array[1]:
course_id: closest time_stamp
unit_id: time_stamp
unit_id: time_stamp
unit_id: time_stamp
unit_id: time_stamp


Follow a sample of the DB query:

array(6) { ["course_id"]=> string(4) "2968" [0]=> string(4) "2968" ["unit_id"]=> string(4) "3002" [1]=> string(4) "3002" ["time_stamp"]=> string(26) "2016-06-10 14:54:11.000000" [2]=> string(26) "2016-06-10 14:54:11.000000" }

array(6) { ["course_id"]=> string(4) "2968" [0]=> string(4) "2968" ["unit_id"]=> string(4) "3006" [1]=> string(4) "3006" ["time_stamp"]=> string(26) "2016-06-10 14:41:54.000000" [2]=> string(26) "2016-06-10 14:41:54.000000" }

array(6) { ["course_id"]=> string(4) "2740" [0]=> string(4) "2740" ["unit_id"]=> string(4) "2982" [1]=> string(4) "2982" ["time_stamp"]=> string(26) "2016-06-10 13:20:01.000000" [2]=> string(26) "2016-06-10 13:20:01.000000" }

array(6) { ["course_id"]=> string(4) "3017" [0]=> string(4) "3017" ["unit_id"]=> string(4) "3012" [1]=> string(4) "3012" ["time_stamp"]=> string(26) "2016-06-10 13:12:19.000000" [2]=> string(26) "2016-06-10 13:12:19.000000" }


I've tried the code below, but it didn't work as expected, because the
array keys
was not filling correct.

foreach ($history as $data) {
if (!array_key_exists($data['course_id'], $courseList)) {
array_push($courseList, $data['course_id']);
$courseList[$data['course_id']] = array();
}

if (count($courseList[$data['course_id']]) <= 4) {
array_push($courseList[$data['course_id']], $data['unit_id']);
}
}

Answer

You're mixing up indexed and associative arrays. You should make $course_array an associative array whose key is the course_id. The value should then be a sub-array that contains all the rows for that course ID.

foreach ($history as $data) {
    $cid = $data['course_id'];
    if (!isset($courseArray[$cid])) {
        $courseArray[$cid] = array();
    }
    $courseArray[$cid][$data['unit_id']] = $data['time_stamp'];
}
Comments