create associative array from any index array


/ Published in: PHP
Save to your folder(s)

converts array (which is reference) in format

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

to

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.