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

Link to comment
Share on other sites

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?

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.