sw9 Posted July 24, 2009 Share Posted July 24, 2009 hi, i have a file that i need to loop through. in that file, there are id numbers and categories. like so: 2, arts 2, leisure 2, sports 3, education 3, sports i need to include these elements into a multidimensional array that ends up looking like so: $categories = array( "2" => array( "arts","leisure", "sports"), "3" => array("education", "sports") ); so as i am looping through, i am trying to push this onto my array like so : <?php array_push($categories[][$id], $cat); ?> but this is apparently not working. can anyone help guide me on how to do this properly? thanks so much. Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted July 24, 2009 Share Posted July 24, 2009 $categories = array(); foreach ($lineFromFile as $line) { list($id,$category) = explode(', ',$line); if (isset($categories[$id])) { $categories[$id][] = $category; } else { $categories[$id] = array($category); } } Quote Link to comment Share on other sites More sharing options...
sw9 Posted July 24, 2009 Author Share Posted July 24, 2009 great! thank you so much, works perfectly. the only thing i am trying to deal with now is dupes, as I sometimes end up with Array ( [21323] => Array ( [0] => 'Sports' [1] => 'Sports' [2] => 'Leisure' [3] => 'Education' ) ) I tried using this function but it doesn't seem to do the trick: <?php function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); } ?> is this because i'm not getting to second array? how would i rewrite that? Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted July 24, 2009 Share Posted July 24, 2009 $categories = array(); foreach ($lineFromFile as $line) { list($id,$category) = explode(', ',$line); if (isset($categories[$id])) { if (!in_array($category,$categories[$id])) { $categories[$id][] = $category; } } else { $categories[$id] = array($category); } } Quote Link to comment Share on other sites More sharing options...
sw9 Posted July 24, 2009 Author Share Posted July 24, 2009 perfect; thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.