如何创建一个新的键名并将数组中的值与PHP组合?

如何创建一个新的键名并将数组中的值与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?

我有2个PHP数组,我需要将值组合在一起。 p>

第一个数组 strong> p>

  array(2){
 [0] => 
数组 (1){
 [“id”] => 
 string(1)“1”
} 
 [1] => 
 array(1){
 [“id”] =>  ; 
 string(2)“40”
} 
} 
  code>  pre> 
 
 

第二个数组 strong> p>

  array(2){
 [0] => 
 string(4)“1008”
 [1] => 
 string(1)“4”
} 
   code>  pre> 
 
 

所需输出 strong> p>

  array(2){
 [0] =>  ; 
 array(1){
 [“id”] => 
 string(1)“1”,
 [“count”] => 
 string(1)“1008”
}  
 [1] => 
 array(1){
 [“id”] => 
 string(2)“40”,
 [“count”] => 
 string(1  )“4”
} 
} 
  code>  pre> 
 
 

如您所见,我需要添加一个新的密钥名称( count code>) 我的第二个数组并将值组合到我的第一个数组。 p>

如何组合输出这个数组? p> div>

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
        )

)