php - Combining array elements into a single one, up to a certain point -



php - Combining array elements into a single one, up to a certain point -

i'm building lifestream-esque sort of blog in php. fetches blog posts mysql database, tweets , last.fm scrobbles.

so far good, i'd combine multiple subsequent scrobbles one. needs remain chronological, though, if blog post or tweet breaks chain of scrobbles, sec part of chain must not combined first part.

array ( [0] => array ( [contents] => disturbed [type] => scrobble [published] => 1327695674 ) [1] => array ( [contents] => amon amarth [type] => scrobble [published] => 1327695461 ) [2] => array ( [contents] => apocalyptica [type] => scrobble [published] => 1327693094 ) [3] => array ( [contents] => tweet. really. [type] => tweet [published] => 1327692794 ) [4] => array ( [contents] => dead sunrise [type] => scrobble [published] => 1327692578 ) )

so since [3] tweet, scrobbles [0]-[2] should combined 1 element. timestamp [published] should set recent of combined elements, , [contents] string set using commas. [4] cannot part of combination, since break chronological order of things.

if you're still me: guess utilize loads of iterations , conditions etc., i'm not sure how handle things performance in mind. array-specific functions use?

$posts = array( /* info here: posts, tweets... */ ); $last_k = null; foreach( $posts $k => $v ) { if( ( null !== $last_k ) && ( $posts[ $last_k ][ 'type' ] == $v[ 'type' ] ) ) { $posts[ $last_k ][ 'contents' ][] = $v[ 'contents' ]; $posts[ $last_k ][ 'published' ] = max( $posts[ $last_k ][ 'published' ], $v[ 'published' ] ); unset( $posts[ $k ] ); continue; } $posts[ $k ][ 'contents' ] = (array)$v[ 'contents' ]; $last_k = $k; }

because 'contents' index array have utilize bring together function output. like:

foreach( $posts $v ) { echo '<div>', $v[ 'type' ], '</div>'; echo '<div>', $v[ 'published' ], '</div>'; echo '<div>', join( '</div><div>', $v[ 'contents' ] ), '</div>'; }

php arrays blogs

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -