3

I have two arrays:

$browser = array("firefox", "opera", "edge");
$version = array("10", "12", "14");

I want to concatenate them such a way that the final array should be:

array(0=>array("name"=>"firefox", "version"=>"10"), 1=>array("name"=>"opera", "version"=>"12"), 2=>array("name"=>"edge", "version"=>"14"));

The code can contain any builtin or user defined function. I have tried using:

$browser = array("firefox","opera","edge");
$version = array("10","12","14");
foreach($browser as $key=>$values){
  if(!isset($array)){
    $array = array("name"=>$browser[$key],"version"=>$version[$key]);
  }else{
    $array = array($array,array("name"=>$browser[$key],"version"=>$version[$key]));
  }
}
print_r($array);

And the output I got was:

Array ( [0] => Array ( [0] => Array ( [name] => firefox [version] => 10 ) [1] => Array ( [name] => opera [version] => 12 ) ) [1] => Array ( [name] => edge [version] => 14 ) ) 

Also note that this code is in PHP and should work for at least 10 arrays length data.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Just in case these separate arrays are coming from an HTML form post (as they often are in questions like this) you can name the inputs so that $_POST already has the final array you're trying to get. – Don't Panic Feb 18 '20 at 19:06

2 Answers2

4

I would just map the arrays:

$result = array_map(function($b, $v) {
                        return ['browser' => $b, 'version' => $v];
                    }, $browser, $version);

You can also use an array for dynamic keys:

$keys = ['browser', 'version'];
$result = array_map(function($b, $v) use($keys) {
                        return array_combine($keys, [$b, $v]);
                    }, $browser, $version);

However with your code just use the first format in the if and dynamically append []:

foreach($browser as $key=>$values){
    $array[] = array("name"=>$browser[$key],"version"=>$version[$key]);
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Reminded me of https://stackoverflow.com/questions/2815162/is-there-a-php-function-like-pythons-zip, but that doesn't include the keys. – Nigel Ren Feb 18 '20 at 18:43
0
$result = array();
for ($i=0; $i<count($browser); $i++) {
  $result[] = array($browser[$i], $version[$i]); 
}
return $result;

Very simple - just loop through the one array and use indexes.

craigmj
  • 4,827
  • 2
  • 18
  • 22