Results 1 to 5 of 5

Thread: [RESOLVED] Create one array from another

  1. #1

    Thread Starter
    Frenzied Member StrangerInBeijing's Avatar
    Join Date
    Mar 2005
    Location
    Not in Beijing
    Posts
    1,666

    Resolved [RESOLVED] Create one array from another

    Say I got one array:
    array('apple', 'banana','apple','orange','orange','apple');
    so i got 3 apples, 1 banana, 2 orange

    I want to turn this into another array where the key is the fruit name, and the value is the number of times that fruit is in the first array

    sth like: array('apple'=>3,'banana=>1,'orange'=>2)

    make sense?

  2. #2
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Create one array from another

    Try this:

    PHP Code:
        $fruits = array('apple''banana','apple','orange','orange','apple');
        
        
    $newFruits = array(); //the new array    FruitName => Count
        
        
    foreach($fruits as $fruit)
        {
            if(
    array_key_exists($fruit$newFruits))
            {
                
    $newFruits[$fruit]++;
            }
            else
            {
                
    $newFruits[$fruit] = 1;
            }
        }

            
    // the for loop builds the new array with the counts, print it out to see the results
        
        
    print_r($newFruits); 
    Chris

  3. #3
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Create one array from another


  4. #4

    Thread Starter
    Frenzied Member StrangerInBeijing's Avatar
    Join Date
    Mar 2005
    Location
    Not in Beijing
    Posts
    1,666

    Re: Create one array from another

    the182guy: Thanks a lot writing some code man. That was exactly what I was looking for, as I also never would imagine the following already exists.

    array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
    Thanks a lot for that penagate.

  5. #5

    Thread Starter
    Frenzied Member StrangerInBeijing's Avatar
    Join Date
    Mar 2005
    Location
    Not in Beijing
    Posts
    1,666

    Re: [RESOLVED] Create one array from another

    I just learned that if you just want to join two arrays and eliminate the duplicate keys, just do a $array1 + $array2. The resulting array will only have the items with same key's once.
    Not very "safe to use" (seeing the items might have same keys, but different values), but that think can be useful sometimes.
    Didn't know.
    Install and Configure Eclipse For both Java and PHP development
    Accessible Ajax/jQuery Forms Degrade gracefully with JavaScript Disabled

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width