How can you combine two arrays?

后端 未结 6 1397
慢半拍i
慢半拍i 2020-12-12 08:15

They are simplified as follows which is enough for this question. This question is based on this answer.

1

[a][b][]

and

2

相关标签:
6条回答
  • 2020-12-12 08:46

    try array_combine()

    http://us2.php.net/manual/en/function.array-combine.php

    0 讨论(0)
  • 2020-12-12 08:49

    PHP provides you a solution to solve this common problem:

    $a = array_merge($b, $c);
    

    With this solution you're going to take all the elements inside $b and merge them with $c. But if you're using associative arrays, you should notice you're going to replace the values in $b with the ones in $c.

    For example:

    <?php
    
    $a = array(
        'ka' => 1,
        'kb' => 1,
    );
    
    $b = array(
        'kb' => 2,
        'kc' => 2,
    );
    
    print_r(array_merge($a, $b));
    
    
    ?>
    

    The result of this code will be something like:

    Array
    (
        [ka] => 1
        [kb] => 2
        [kc] => 2
    )
    
    0 讨论(0)
  • 2020-12-12 08:56

    $array1 = array_merge($array1, $array2);

    0 讨论(0)
  • 2020-12-12 08:59

    Ok, I see what you're talking about. (For everyone else, see the link he posted: http://dpaste.com/81464/)

    var $output = array();
    
    foreach ($array1 as $index => $a1) {
        $output[$index] = $a1;
        $output[$index]['title'] = $array2[$index]['title'];
    }
    
    0 讨论(0)
  • 2020-12-12 09:06
    for($i = 0; $i < sizeof($array); $i++)
    {
         $mergedarray[a][b] = $a[a][b];
         $mergedarray[a][c] = $b[a][c];
    }
    

    as far as i can tell this is what you want, that way both the sub-keys have the same root key.

    0 讨论(0)
  • 2020-12-12 09:08
    foreach($array1 as $a => $c)
    {
        $end_array[$c] = $array2[$a];
    }
    

    or

    // For every [a]
    foreach($array1 as $a => $c)
    {
        // Get the [b]
        $b = $array2[$a];
    
        // Add it to [a][c]
        $end_array[$a][$c] = $b;
    
        // Making it $end_array[$a][$c][$b] = array(....);
    }
    
    0 讨论(0)
提交回复
热议问题