Strategies for Custom Array Functionality in PHP -
i find myself struggling finding solution various array arrangement problems in php fall outside of solutions have implemented before.
currently, starting array:
$tags = array( array('tag_id' => 1, 'tag_name' => 'hello', 'album_id => 1'), array('tag_id' => 1, 'tag_name' => 'hello', 'album_id => 2'), array('tag_id' => 2, 'tag_name' => 'world', 'album_id => 1'), array('tag_id' => 2, 'tag_name' => 'world', 'album_id => 2'), array('tag_id' => 3, 'tag_name' => 'again', 'album_id => 3') );
and want organize such:
$organized_tags = array( array('tag_id' => 1, 'tag_name' => 'hello', 'album_ids' => array(1,2)), array('tag_id' => 2, 'tag_name' => 'world', 'album_ids' => array(1,2)), array('tag_id' => 3, 'tag_name' => 'again', 'album_ids' => array(3)) );
a) best strategy solving kind of problem? b) how think solving generic array problems come in future?
i might take leaf book of cakephp in representing model data arrays.
with this, have tag model, , album model. data give, tag model looks like
['tag' => ['tag_id' => 1, 'tag_name' => 'hello']]
and, moment, album has id
['album' => ['album_id' => 1']]
to represent organized structure:
[ 0 => [ 'tag' => ['tag_id' => 1, 'tag_name' => 'hello'], 'album' => [ 0 => ['album_id' => 1], 1 => ['album_id' => 2] ], 1 => [ 'tag' => ['tag_id' => 2, 'tag_name' => 'world'], 'album' => [ 0 => ['album_id' => 1], 1 => ['album_id' => 2] ], 2 => [ 'tag' => ['tag_id' => 3, 'tag_name' => 'again'], 'album' => [ 0 => ['album_id' => 3] ] ]
however, isn't you've asked for.
to change $tags
$organized_tags
, i'd tag
model class takes $tags
structure, iterates through it, , builds second structure.
public function toorganizedtags($tags) { $organizedtags = []; foreach ($tags $tag) { if (!isset($organizedtags[$tag['tag_id']]) { // make sure entry exists. assume tag_name not change between similar tag_id entries. $organizedtags[$tag['tag_id']] = [ 'tag_id' => $tag['tag_id'], 'tag_name' => $tag['tag_name'], 'album_ids' => [] ]; } $organizedtags[$tag['tag_id']]['album_ids'][] = $tag['album_id']; } // use array_values strip indexed keys return array_values($organizedtags); }
Comments
Post a Comment