Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an array from an associative array using one of its value in a key value pair

I’ve a following associative array named $data. Here is some same key value pairs

 Array
   (
      [0] => Array
      (
        [id] => 1
        [config_id] => 31
        [language] => "English"
      )

      [1] => Array
      (
        [id] => 2
        [config_id] => 33
        [language] => "English"
      )
      [2] => Array
      (
        id] => 3
        [config_id] => 32
        [language] => "French"
      )

   )

And i wanted to convert this array as

Array
   (
      ["English"] => Array(
       [0]=> Array
        (
        [id] => 1
        [config_id] => 31
       )

       [1] => Array
       (
        [id] => 2
        [config_id] => 33
       )
      )
      ["French"] => 
      Array(
       [0]=> Array
        (
        [id] => 3
        [config_id] => 32
        )
      )
     )
   )

I need the language as key in the output array,Can anyone help me out to resolve this issue? Thanks in advance.
I tried the following code, but printed the last array value only

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     $arry = array();
     foreach ($data as $val) {
        
        $arry[$val->language]["config_id"] =  $val->id;
        $arry[$val->language]["config_id"] =  $val->config_id;
     }

>Solution :

You are nearly there, just need to make the new array all in one go and just use the $arry[$val->language][] to create a new sub array under that new or existing language key.

Also $data is an array or arrays not an array of objects so the addressing of the items was wrong.

$arry = array();
foreach ($data as $val) {
    $arry[$val->language][] =  ['id' => $val['id'], 'config_id' => $val['config_id']];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading