Posted By

slav123 on 02/22/11


Tagged

php array associative


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


create associative array from any index array


 / Published in: PHP
 

converts array (which is reference) in format

array(0 => array('id' => 1, 'name' => 'orange'), 1 => array('id' => 3, 'name' => 'banana'));

to

array(1 => array('id' => 1, 'name' => 'orange'), 3 => array('id' => 3, 'name' => 'banana'));

  1. public function make_assoc(&$arr, $key = 'id') {
  2. $tmp = $arr;
  3.  
  4. $max = count($arr);
  5. $kold = array();
  6. $knew = array();
  7. for ($a = 0;$a<$max;$a++) {
  8. $kold[] = $a;
  9. $knew[] = $tmp[$a][$key];
  10. $arr[$tmp[$a][$key]] = $tmp[$a];
  11. }
  12.  
  13. unset($tmp);
  14. $dif = array_diff($kold,$knew);
  15. foreach ($dif as $d) unset($arr[$d]);
  16. }

Report this snippet  

You need to login to post a comment.