When I retrieve articles information from a mysql database I got an array like this:
Array ( [0] => Array ( [CategoryID] => 3 [CategoryName] => Test Category [Parent] => 0 [Thumb] => 0 [sort] => 8 [ArticleID] => 2 [ArticleCatgories] => 9,4,3 [ArticleTitle] => vxcvxcvx [ArticleBody] => xcvxcvxcvxcv [InGroup] => 0 [GroupID] => 0 [Published] => 1 [PublishTime] => [TermID] => 11 [TermSlug] => xcvxcvxcv [RelatedID] => 2 [TermType] => article ) [1] => Array ( [CategoryID] => 4 [CategoryName] => Test Image [Parent] => 0 [Thumb] => 0 [sort] => 4 [ArticleID] => 2 [ArticleCatgories] => 9,4,3 [ArticleTitle] => vxcvxcvx [ArticleBody] => xcvxcvxcvxcv [InGroup] => 0 [GroupID] => 0 [Published] => 1 [PublishTime] => [TermID] => 11 [TermSlug] => xcvxcvxcv [RelatedID] => 2 [TermType] => article ) [2] => Array ( [CategoryID] => 9 [CategoryName] => Test Images [Parent] => 0 [Thumb] => 7 [sort] => 2 [ArticleID] => 2 [ArticleCatgories] => 9,4,3 [ArticleTitle] => vxcvxcvx [ArticleBody] => xcvxcvxcvxcv [InGroup] => 0 [GroupID] => 0 [Published] => 1 [PublishTime] => [TermID] => 11 [TermSlug] => xcvxcvxcv [RelatedID] => 2 [TermType] => article ) }
And because the article is in more than one category, it retrieve the article information more than once. What I need to do is to combine the category names into a sub array if they have the same ArticleID so the result become like:
Array ( [0] => Array ( [CategoryName] => array('Test Category','Test Image','Test Images'); [Parent] => 0 [Thumb] => 0 [sort] => 8 [ArticleID] => 2 [ArticleCatgories] => 9,4,3 [ArticleTitle] => vxcvxcvx [ArticleBody] => xcvxcvxcvxcv [InGroup] => 0 [GroupID] => 0 [Published] => 1 [PublishTime] => [TermID] => 11 [TermSlug] => xcvxcvxcv [RelatedID] => 2 [TermType] => article ) }
Advertisement
Answer
You can build a new array using ArticleID
as the keys:
$final = array(); foreach ($rows as $row) { $id = $row['ArticleID']; if (isset($final[$id])) { // we've already seen this article // append to categoryname array $final[$id]['CategoryName'][] = $row['CategoryName']; } else { // this is the first article occurrence // turn categoryname into array first $row['CategoryName'] = array($row['CategoryName']); $final[$id] = $row; } } print_r($final);
Output based on your question:
Array ( [2] => Array ( [CategoryID] => 3 [CategoryName] => Array ( [0] => Test Category [1] => Test Image [2] => Test Images ) [Parent] => 0 [Thumb] => 0 [sort] => 8 [ArticleID] => 2 [ArticleCatgories] => 9,4,3 [ArticleTitle] => vxcvxcvx [ArticleBody] => xcvxcvxcvxcv [InGroup] => 0 [GroupID] => 0 [Published] => 1 [PublishTime] => [TermID] => 11 [TermSlug] => xcvxcvxcv [RelatedID] => 2 [TermType] => article ) )