Simon Orro
Simon Orro

Reputation: 204

How to create a new key name and combine values in array with PHP?

I have 2 PHP arrays that I need to combine values together.

First Array

array(2) {
    [0]=>
    array(1) {
        ["id"]=>
        string(1) "1"
    }
    [1]=>
    array(1) {
        ["id"]=>
        string(2) "40"
    }
}

Second Array

array(2) {
    [0]=>
    string(4) "1008"
    [1]=>
    string(1) "4"
}

Output desired

array(2) {
    [0]=>
    array(1) {
        ["id"]=>
        string(1) "1",
        ["count"]=>
        string(1) "1008"
    }
    [1]=>
    array(1) {
        ["id"]=>
        string(2) "40",
        ["count"]=>
        string(1) "4"
    }
}

As you can see I need to add a new key name (count) to my second array and combine values to my first array.

What can I do to output this array combined?

Upvotes: 1

Views: 78

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Another functional approach (this won't mutate/change the initial arrays):

$arr1 = [['id'=> "1"], ['id'=> "40"]];
$arr2 = ["1008", "4"];

$result = array_map(function($a){
    return array_combine(['id', 'count'], $a);
}, array_map(null, array_column($arr1, 'id'), $arr2));

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [id] => 1
            [count] => 1008
        )

    [1] => Array
        (
            [id] => 40
            [count] => 4
        )
)

Upvotes: 1

Oleksandr Tymchenko
Oleksandr Tymchenko

Reputation: 1

Or another approach with recursion:

$arr1=[["id"=>1],["id"=>40]];
$arr2=[1008,4];

foreach ($arr1 as $key=>$value) {
    $result[] = array_merge_recursive($arr1[$key], array ("count" => $arr2[$key]));
}

print_r($result);

And output:

Array
(
    [0] => Array
        (
            [id] => 1
            [count] => 1008
        )

    [1] => Array
        (
            [id] => 40
            [count] => 4
        )

)

Upvotes: 0

freelancer
freelancer

Reputation: 1164

you can do it like this

$arr1=[["id"=>1],["id"=>40]];
$arr2=[1008,4];
for($i=0;$i<count($arr2);$i++){
  $arr1[$i]["count"] = $arr2[$i];
}

Live demo : https://eval.in/904266

output is

Array
(
    [0] => Array
        (
            [id] => 1
            [count] => 1008
        )

    [1] => Array
        (
            [id] => 40
            [count] => 4
        )

)

Upvotes: 1

Claudio
Claudio

Reputation: 5213

Try something like the following. The idea is to iterate on the first array and for each array index add a new key "count" that holds the value contained on the same index of the second array.

$array1 = [];
$array2 = [];

for ($i = 0; $i < count($array1); $i++) {
    $array1[$i]['count'] = $array2[$i];
}

Upvotes: 2

Related Questions