简体   繁体   中英

Mergin two arrays but keep indexes

So I have these two arrays that I need to merge into one and keep the indexes. I tried different things like array_merge , array_merge_recursive , etc but I couldn't figure it out.

array(3) {
  [0]=>
  string(4) "Peter"
  [1]=>
  string(4) "Josh"
  [2]=>
  string(4) "Jasper"
}
array(3) {
  [0]=>
  string(2) "18"
  [1]=>
  string(2) "19"
  [2]=>
  string(2) "25"
}

This is how I want it to look like:

array(3) {
  [0]=>
  array(2) {
    ["name"]=>
    string(5) "Peter"
    ["age"]=>
    int(18)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "Josh"
    ["age"]=>
    int(19)
  }
}

Any ideas how I can achieve this?

Try This:

$array1 = array(0 => 'Peter', 1 => 'Josh', 2 => 'Jasper');
$array2 = array(0 => '18', 1 => '19', 2 => '25');
for($i = 0; $i<count($array1); $i++){
   $newArray[] = array("name" => $array1[$i], "age" => $array2[$i]);
}
var_dump($newArray);

This is something I've used before as more reusable decision in case you want to add for example not only Name, Age, but Email or something else later.

Posting below code with explained comments.

<?php

// Array containing names
$namesArr = array(
    'Peter', 
    'Josh', 
    'Jasper'
);

// Array containing ages
$agesArr = array(
    18,
    19,
    25
);

$arrayDesign = array(
    'name' => $namesArr, 
    'age'  => $agesArr
);

/**
 * Combines given array design into one grouped by keys.
 * Example Input:
 *      $design => array(
 *          'name' => array('Name1', 'Name2'), 
 *          'age'  => array(10, 20)
 *      );
 * Example Output:
 *      $output => array(
 *          0 => array(
 *              'name' => 'Name1', 
 *              'age' => 10
 *          ), 
 *          1 => array(
 *              'name' => 'Name2', 
 *              'age' => 20
 *          )
 *      );
 * 
 * @param Array $arrayDesign
 * 
 * @return Array combined array
 */
function combineArraysByKeys($arrayDesign) {

    // Holds results
    $results = array();

    // Get size of first element from the design, so we'll know the size of rest elements.
    $designElementSize = count($arrayDesign[array_keys($arrayDesign)[0]]);

    // Count from-to elements
    for($c = 0; $c < $designElementSize; $c++) {

        // Define array as part of results to be added after population
        $arrayPart = array();

        // Loop thru all keys and get values
        foreach(array_keys($arrayDesign) as $key) {

            // Assign value to key
            $arrayPart[$key] = $arrayDesign[$key][$c];
        }

        // Add to results array
        $results[] = $arrayPart;
    }

    return $results;
}

$result = combineArraysByKeys($arrayDesign);

echo "<PRE>";
print_r($result);
die();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM