Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to key map an array in php

I have an array as follows

array(2) { ["name"]=> string(36) "newyork" ["categoryid"]=> string(1) "4" }                                                                                                                                                                                                            
array(2) { ["name"]=> string(24) "michigun" ["categoryid"]=> string(1) "4" } 
array(2) { ["name"]=> string(27) "canada" ["categoryid"]=> string(1) "5" }             
array(2) { ["name"]=> string(35) "manhatten" ["categoryid"]=> string(1) "5"   
}

i want to have a new array where i will have

 {"4" => newyork,michigun}
 {"5" => canada,manhatten}

.. how can it be done? pls help.

like image 854
Ketki Nimdeo Avatar asked Jun 24 '26 01:06

Ketki Nimdeo


1 Answers

You can use a loop and build the array -

$new = array();
foreach($your_array as $array) {
   if(array_key_exists($array['categoryid'], $new)) { // if categoryid is already set the concatenate the name
       $new[$array['categoryid']] = $new[$array['categoryid']] . ',' . $array['name'];
   } else { // set the name
       $new[$array['categoryid']] = $array['name'];
   }
}
like image 87
Sougata Bose Avatar answered Jun 25 '26 15:06

Sougata Bose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!