我有一个变量$items
,其中包含以下数据。
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
)
)
我想对数据进行分类。 course_id应该成为关键,具有类似course_id的课程应该被分类并成为该关键的价值。就像在about数组中一样,[1],[2]和[3]具有相同的course_id,因此for key => 6,应该使用具有文档73,75和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',
)),
)
答案 0 :(得分:3)
试试这个: 使用get_object_vars将obj转换为数组。
$newarray = array();
foreach ($items as $item)
{
$newarray[$item->course_id][] = get_object_vars($item);
}