Jump to content

[SOLVED] array_push question


sw9

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/167296-solved-array_push-question/
Share on other sites

$categories = array();
foreach ($lineFromFile as $line) {
   list($id,$category) = explode(', ',$line);
   if (isset($categories[$id])) {
      $categories[$id][] = $category;
   } else {
      $categories[$id] = array($category);
   }
}

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?

 

$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);
   }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.