Home > Software design >  Create an array from an associative array using one of its value in a key value pair
Create an array from an associative array using one of its value in a key value pair

Time:12-08

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

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

CodePudding user response:

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']];
}
  • Related