[PHP]: Handling Multidimensonal Array

bhupendra2895

New Member
Messages
554
Reaction score
20
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?
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
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.
 

bhupendra2895

New Member
Messages
554
Reaction score
20
Points
0
@ Misson Thanks, What you described above is a better way to solve the problem.
 
Top