简体   繁体   中英

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?

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];
}

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
        )

)

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
        )
)

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
        )

)

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