0

Please check attached images. These image contains $complex_arr print and $simple_arr print results. I want to convert $complex_arr to $simple_arr output.

How is that possible? What is actually doing each of $complex_arr inside value will be converted as associative simple array like $simple_arr

$arr1 = array("asso1"=>"a", "asso2"=>"1");
$arr2 = array("asso1"=>"b", "asso2"=>"2");
$arr3 = array("asso1"=>"c", "asso2"=>"3");

$complex_arr = array($arr1,$arr2,$arr3);
$simple_arr = array("a"=>"1", "b"=>"2", "c"=>"3");

// print_r($complex_arr);
print_r($simple_arr);

Input:

complex picture

Output:

simple picture

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Smith Kr
  • 25
  • 2

3 Answers3

1

You have to write it on our own... here is my idea:

public function makeItSimpler($arr){
   $newarr = array();
   foreach($arr as $complex){
      $newarr[$complex['asso1']]=$complex['asso2'];
   }
   return $newarr;
}

Perhaps you can do it better... take look at "array-map" http://php.net/manual/de/function.array-map.php Good Luck

fucethebads
  • 471
  • 1
  • 5
  • 10
1
foreach ($complex_arr as $key => $value) {
            $simple_arr[$value['asso1']]=$simple_arr[$value['asso2']];
        }
1

With php5.5 (where array_column becomes available) it is:

$simple_arr = array_combine(
    array_column($complex_arr, 'asso1'),
    array_column($complex_arr, 'asso2')
);

And even simplier (after I reread function manual):

$simple_arr = array_column($complex_arr, 'asso2', 'asso1');
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Thanks, I've learnt a new method... Just one wee thing, the 2nd parameter shouldn't have the comma on the end as it makes the function call expect a missing and unwanted third parameter. – TimBrownlaw Dec 20 '16 at 08:05
  • @TimBrownlaw thanks, edited. – u_mulder Dec 20 '16 at 08:06