Forum Moderators: coopster

Message Too Old, No Replies

Splitting up an array

Splitting Arrays

         

kyler

2:11 pm on Jan 21, 2005 (gmt 0)

10+ Year Member



Hi all

I have an array I would like to split apart based on the data's second colum and print it out to a html table using the second colum category as headings?

Table Structure/ARRAY:

Array (
3, Senator, n, JR P cloudy (D - Manitoba)
4, Senator, n, JR P cloudy (D - Manitoba)
5, Senator, n, JR P cloudy (D - Manitoba)
6, Candidate, n, JR P cloudy (D - Manitoba)
7, Candidate, n, JR P cloudy (D - Manitoba)
8, Other, n, JR P cloudy (D - Manitoba)
9, Congress, n, JR P cloudy (D - Manitoba)
)

IE : table

Senator
JR P cloudy (D - Manitoba)
JR P cloudy (D - Manitoba)
JR P cloudy (D - Manitoba)

Candidate
JR P cloudy (D - Manitoba)
JR P cloudy (D - Manitoba)

Other
JR P cloudy (D - Manitoba)

etc........

Birdman

2:57 pm on Jan 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think array chunk will come in handy here. The code below assumes you already have an array as you posted above. If you need to get a comma delimited string into an array to start, use:

$input_array = explode(',', $string);


$arr = array_chunk($input_array, 4);
unset( $input_array );
$newarr = array();

foreach ( $arr as $val ){

if (!array_key_exists( $val[1] ), $newarr ) {
$newarr[$val[1]] = '';
}

$newarr[$val[1]] .= '<p>' . $val[3] . '</p>';

}
unset( $arr );

//OUTPUT HTML
foreach ( $newarr as $key => $val ) {
print '<h2>' . $key . '</h2>' . $val;
}