Home > OS >  How to join two arrays by putting one at the end of each array?
How to join two arrays by putting one at the end of each array?

Time:11-20

I have two arrays like this:

$a = array (1 => [
                       1 => "a",
                       2 => "b",
                       3 => "c"]
                    2 => [
                        1 => "d",
                        2 => "e",
                        3 => "f"]
                    3 => [
                        1 => "g",
                        2 => "h",
                        3 => "i"]);

$b = array (1 => "1", 2 => "2", 3 => "3");

I need the two arrays to be as follows

$a = array (1 => [
                       1 => "a",
                       2 => "b",
                       3 => "c",
                       4 => 1]
                    2 => [
                        1 => "d",
                        2 => "e",
                        3 => "f",
                        4 => 2]
                    3 => [
                        1 => "g",
                        2 => "h",
                        3 => "i",
                        4 => 3]
);

In such a way that the two arrays are united and the elements of array $b remain at the end of array $a

Thank you very much to all.

CodePudding user response:

You can achieve it like this:

foreach ($a as $key => $value) {
    if (isset($b[$key])) $a[$key][count($a[$key])   1] = $b[$key];
}

Explanation:

  • we iterate our $a array
  • $key is the index of its current array
  • we ensure that we only add the element from $b if it exists in order to avoid errors
  • we add the correct element to $a[$key] at its count($a[$key]) 1 index, since the count was 3, count 1 is 4

CodePudding user response:

This solution can help you:

$a = [
    1 => [
        1 => "a",
        2 => "b",
        3 => "c"
    ],
    2 => [
        1 => "d",
        2 => "e",
        3 => "f"
    ],
    3 => [
        1 => "g",
        2 => "h",
        3 => "i"
    ]
];

$b = [
    1 => "1", 
    2 => "2", 
    3 => "3"
];

$result = [];
array_walk($a, function($item, $key, $b) use (&$result) {
    $result[$key] = array_merge($item, (array) $b[$key]);
}, $b);

The var_dump of this solution:

array(3) {
  [1]=>
  array(4) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
    [3]=>
    string(1) "1"
  }
  [2]=>
  array(4) {
    [0]=>
    string(1) "d"
    [1]=>
    string(1) "e"
    [2]=>
    string(1) "f"
    [3]=>
    string(1) "2"
  }
  [3]=>
  array(4) {
    [0]=>
    string(1) "g"
    [1]=>
    string(1) "h"
    [2]=>
    string(1) "i"
    [3]=>
    string(1) "3"
  }
}

This is a link of the code if you want to test it: http://sandbox.onlinephpfunctions.com/code/a8548fff9271c76d9c8b57a2c6baee93fcad0e01

I hope that I was helpful.

  • Related