[PHP]: Handling Multidimensonal Array

Discussion in 'Scripts, 3rd Party Apps, and Programming' started by bhupendra2895, Dec 12, 2010.

  1. bhupendra2895

    bhupendra2895 New Member

    Messages:
    554
    Likes Received:
    20
    Trophy Points:
    0
    I have a array that looks like
    Code:
    Array
    (
        [0] => Array
            (
                [link] => http://updated
                [type] => x10
                [vote] => 2
            )
    
        [1] => Array
            (
                [link] => http://latest
                [type] => hosting
                [vote] => 1
            )
    
        [2] => Array
            (
                [link] => http://paid
                [type] => x10
                [vote] => 3
            )
    
        [3] => Array
            (
                [link] => http://free
                [type] => hosting
                [vote] => 5
            )
    )
    
    I want the result like this

    Code:
    Array(
             [x10] => Array
                      (
                            [link1] => http://updated
                            [vote1] => 2
                            [link2] => http://paid
                            [vote2] => 3
                      )
             [hosting] => Array
                      (
                            [link1] => http://latest
                            [vote1] => 1
                            [link2] => http://free
                            [vote2] => 5
                      )
    )               
    
    I am trying to find the solution of above problem since many hours.

    How this can be solved?
     
  2. misson

    misson Community Paragon Community Support

    Messages:
    2,572
    Likes Received:
    72
    Trophy Points:
    48
    Iterate over the array, filling out another array.
    PHP:
    foreach ($source as $entry) {
        
    $byType[$entry['type']][] = $entry;
    }
    var_export($byType);
    /*Result: 
    array (
      'x10' => 
      array (
        0 => 
        array (
          'link' => 'http://updated',
          'type' => 'x10',
          'vote' => 2,
        ),
        1 => 
        array (
          'link' => 'http://paid',
          'type' => 'x10',
          'vote' => 3,
        ),
      ),
      'hosting' => 
      array (
        0 => 
        array (
          'link' => 'http://latest',
          'type' => 'hosting',
          'vote' => 1,
        ),
        1 => 
        array (
          'link' => 'http://free',
          'type' => 'hosting',
          'vote' => 5,
        ),
      ),
    )
    */
    Don't use 'link1', 'vote2' &c. as indices; use subarrays.
     
  3. bhupendra2895

    bhupendra2895 New Member

    Messages:
    554
    Likes Received:
    20
    Trophy Points:
    0
    @ Misson Thanks, What you described above is a better way to solve the problem.
     

Share This Page