Home > Back-end >  array merge return keys
array merge return keys

Time:10-22

I have an array:

Array
(
    [0] => Array
        (
            [aaa] => 111
        )

    [1] => Array
        (
            [bbb] => 222
        )

    [2] => Array
        (
            [bbb] => 333
        )

)

I want to get:

Array
(      
[aaa] => 111
[bbb] => 333
)

My code. Is this a good feature for that? :

function myfunction($num)
{
  return $x[array_keys($num)] = array_values($num);
}
$a = array_map("myfunction",$a);

Is it even possible? What features to use?

CodePudding user response:

$finalArray = []    
foreach ($topArray as $array) {
  foreach ($array as $key => $value) {
      $finalArray[$key] = $value;
  }
}

CodePudding user response:

After php v5.6 you are able to do just the following $b = array_merge(...$a); In JavaScript for modern browsers it known as flatMap (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)

Complete scenario:

<?php
    
    $a = array(
        array('aaa' => 111), 
        array('bbb' => 222),
        array('bbb' => 333),
    );
    $b = array_merge(...$a);
    var_dump($b);

?>

http://sandbox.onlinephpfunctions.com/code/390ed3354e39a8db1d59abfb79dbbd59aec7f92c

  • Related