Ali Zia Ali Zia - 3 months ago 8
PHP Question

Group objects in php with similar course_id

I have a variable

$items
that has following data inside it.

Array
(
[0] => stdClass Object
(
[course_id] => 8
[doc_id] => 85
[doc_title] => PDF Notes
[doc_price] => 243
)

[1] => stdClass Object
(
[course_id] => 6
[doc_id] => 73
[doc_title] => PDF Notes
[doc_price] => 12
)

[2] => stdClass Object
(
[course_id] => 6
[doc_id] => 75
[doc_title] => Audio Topics
[doc_price] => 21
)

[3] => stdClass Object
(
[course_id] => 6
[doc_id] => 77
[doc_title] => Video Past Papers
[doc_price] => 32
)

)


I want to categorize the data. The course_id should become the key and the courses that have similar course_id should be categorized and become the value of that key. Like in the about array, [1], [2] and [3] have same course_id so the for key => 6, an array should be made with sub array that have docs 73, 75 and 77.

array => (
'6' => 'array of docs with course_id 6',
'8' => 'array of docs with course_id 8',
)


VAR_EXPORT

array (
0 =>
stdClass::__set_state(array(
'course_id' => '8',
'doc_id' => '85',
'doc_title' => 'PDF Notes',
'doc_price' => '243',
)),
1 =>
stdClass::__set_state(array(
'course_id' => '6',
'doc_id' => '73',
'doc_title' => 'PDF Notes',
'doc_price' => '12',
)),
2 =>
stdClass::__set_state(array(
'course_id' => '6',
'doc_id' => '75',
'doc_title' => 'Audio Topics',
'doc_price' => '21',
)),
3 =>
stdClass::__set_state(array(
'course_id' => '6',
'doc_id' => '77',
'doc_title' => 'Video Past Papers',
'doc_price' => '32',
)),
)

Ish Ish
Answer

Try this: use get_object_vars to convert obj to array.

$newarray = array();
foreach ($items as $item)
{
  $newarray[$item->course_id][] = get_object_vars($item); 
}