Create new arrays from a parent based on key=>val?
Posted: Fri Dec 18, 2009 10:59 am
I have an array of records with a key named 'news_type_id', which can be an intval from 1-4.
Each int is an id for a lookup table that contains the news_type_id and the news type:
What I'd like to do is create a new array for each news_type_id found in the original record array so that I can display the records in the view segregated by news_type:
Is there an efficient way to do this? Right now, I'm querying the db, which produces the first array above:
Then I'm doing a switch on the result array:
Seems rather clunky, although it works. But what I'd like to do is rewrite the code so I can use any number of news_type_ids and have it automatically create the separate arrays, ideally by querying the lookup table (right now, I'm manually coding the switch statement based on the news_types, which I know in advance). If the client wants to add different types I'd like to not have to go back into the code to reflect them.
Thanks for your input.
Code: Select all
$records = array(
array('news_type_id'=>2,'content'=>'Some content'),
array('news_type_id'=>1,'content'=>'Some content'),
array('news_type_id'=>3,'content'=>'Some content'),
array('news_type_id'=>3,'content'=>'Some content'),
array('news_type_id'=>1,'content'=>'Some content'),
array('news_type_id'=>4,'content'=>'Some content'),
array('news_type_id'=>2,'content'=>'Some content')
);
Code: Select all
[u]"news_type_id" "type"[/u]
"1" "Press Releases"
"2" "Company News"
"3" "Partner News"
"4" "Published Articles"
Code: Select all
$records['Press Releases'] = array(
array('news_type_id'=>1,'content'=>'Some content'),
array('news_type_id'=>1,'content'=>'Some content')
);
$records['Company News'] = array(
array('news_type_id'=>2,'content'=>'Some content'),
array('news_type_id'=>2,'content'=>'Some content')
);
$records['Partner News'] = array(
array('news_type_id'=>3,'content'=>'Some content'),
array('news_type_id'=>3,'content'=>'Some content')
);
$records['Published Articles'] = array(
array('news_type_id'=>4,'content'=>'Some content')
);
Code: Select all
SELECT *
FROM (`news`)
Code: Select all
foreach ($records as $r){
switch($r['news_type_id']){
case 1:
$types['Press Releases'] []= $r;
break;
case 2:
$types['Focus News'] []= $r;
break;
case 3:
$types['Partner News'] []= $r;
break;
case 4:
$types['Published Articles'] []= $r;
break;
}
}
Thanks for your input.