PHP - structure multidimensional array depending on values -


i have array:

$initialarray = array(   0 = array(     'unit' => 1,     'class' => 1,     'value' => 'string1'   ),   1 = array(     'unit' => 1,     'class' => 2,     'value' => 'string2'   ),   2 = array(     'unit' => 1,     'class' => 2,     'value' => 'string3'   ),   3 = array(     'unit' => 2,     'class' => 1,     'value' => 'string4'   )   4 = array(     'unit' => 2,     'class' => 2,     'value' => 'string5'   ) ); 

what best way structure (to group resulting sub-arrays) depending first on 'unit' field's values, , depending on 'class' field's values, so:

$resultarray = array(   // array of sub-arrays of 'unit' = 1   $unit[1] = array(     // array of sub-arrays of 'unit' = 1 , 'class' = 1     $class[1] = array(       0 = array(         'unit' => 1,         'class' => 1,         'value' => 'string1'       )     )     // array of sub-arrays of 'unit' = 1 , 'class' = 2     $class[2] = array(       0 = array(         'unit' => 1,         'class' => 2,         'value' => 'string2'       ),       1 = array(         'unit' => 1,         'class' => 2,         'value' => 'string3'       )     )   )   // array of sub-arrays of 'unit' = 2   $unit[2] = array(     // array of sub-arrays of 'unit' = 2 , 'class' = 1     $class[1] = array(       0 = array(         'unit' => 2,         'class' => 1,         'value' => 'string4'       )     )     // array of sub-arrays of 'unit' = 2 , 'class' = 2     $class[2] = array(       0 = array(         'unit' => 2,         'class' => 2,         'value' => 'string5'       )     )   ) ) 

i have asked similar question here , got working answer 1 iteration, i.e. structuring array 1 of fields. not make same solution work multiple iterations, i.e. more 1 field.

also, there solution structure multidimensional array depending on more 2 fields?

i think it's not way of asking question. simple , can playing arrays,keys , etc.... first should try hard problem. after if have problem in middle of tries can ask here. have solved problem here complete code , next time please work , post problem. never ask code.

foreach ($initialarray $key1=>$val1) {     foreach ($val1 $key2=>$val2)     {                      if($key2=='unit')         {             $num=$val2;             if($val2!=$num)             $testarr['unit'.$val2]=array();         }         if($key2=='class')         {             $testarr['unit'.$num]['class'.$val2][]=$val1;         }      } }  print_r($testarr); 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -