Array combine into associative array

不问归期 提交于 2019-12-11 14:44:05

问题


I need to add the values of an associative array to another one.

$a = array(4=>2,5=>5);
$b = arrray(array(0=>0,1=>4,2=>10,3=>1000),array()...);

What I'm expecting to get is a third array ($c) like the one below where the content of $b follows the content of $a:

$c = array(array(4=>2,5=>5,0=>0,1=>4,2=>10,3=>1000),array(4=>2,5=>5....));

This is what I've written (not working):

$c = array();
foreach ($possible_opp_action as $sub) {
    $c[] = array_push($to_merge,array_values($sub));

}

回答1:


$a = array(4=>2,5=>5);
$b = array(array(0=>0,1=>4,2=>10,3=>1000),
           array(0=>0,1=>40,2=>100,3=>2000),
           array(4=>10)
          );

$c = array();
foreach($b as $tmp) {
    $c[] = $a+$tmp;
}

var_dump($c);

Unlike array_merge, this will maintain numeric keys... but watch out for duplicate keys




回答2:


$c = array();
foreach ($b as $bb) {
    $c[] = array_merge($a,$bb);
}



回答3:


If you do not need $b in original form:

<?php

$a = array(4=>2,5=>5);
$b = array(array(0=>0,1=>4,2=>10,3=>1000),array());

foreach ($b as &$ref) {
    $ref = $a + $ref;
}

var_dump($b);

Otherwise:

<?php

$a = array(4=>2,5=>5);
$b = array(array(0=>0,1=>4,2=>10,3=>1000),array());

$c = array();

foreach ($b as &$ref) {
    $c[] = $a + $ref;
}

var_dump($c);



回答4:


You need array_merge.

http://us.php.net/manual/en/function.array-merge.php

Note the handling of duplicate keys:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

EDIT:

I may have not read the question right - please clarify...

Do you want all the array items in a single array, or an array with the original arrays as items in it (an array of arrays)?

IE: c = array(a=a, b=b, c=c, etc.) <- can be done with array_merge($a, $b, $c, etc)

vs

c = array( b = array(a=a, b=b, c=c, etc), a=array(d=d, e=e, etc.) ) <- should be done by just concatenating the next array on the end like this (and skip the $c altogether):

$c[] = $b;
$c[] = $a;

//or

$c = array();
foreach ($possible_opp_action as $sub) {
    $c[] = $sub;    
}



回答5:


try

$c = array_merge($b, $a)

help in http://php.net/manual/es/function.array-merge.php



来源:https://stackoverflow.com/questions/8662157/array-combine-into-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!