在php中组合两个数组

在php中组合两个数组

问题描述:

I have two array in php and now I want to combine this two array as below.

$a1 = Array(
    'ansid4' => 4,
    'ansid5' => 5,
    'ansid6' => 6
);

$a2 = Array(
    'value' => 'demo',
    'value2' => 'demo2'
);

Required Output:

$target = Array(
    4 => 'demo',
    5 => 'demo2',
    6 => Null
);

Thanks in advance

$resultArray = array();

while ($key = array_pop($arrayOne)) {
  $resultArray[$key] = array_pop($arrayTwo);
}

or you could do

$resultArray = array();

foreach ($arrayOne as $key) {
  $resultArray[$key] = array_shift($arrayTwo);
}

Both solutions have the disadvantage that they consume one or both arrays. If you need them still after the combination you could make copies of the Arrays and have those consumed.

Take a look at array_combine you can send to this function array of keys and array of values and it return assoc array

please notice that the two arrays must have the same number of elements. if you cant take care of that, try using array_pad before

$targetArray = array('a'=>'','b'=>''); 
$sourceArray = array('a'=>array(1,2,3),'c'=>'c','d'=>'d');
$result = array_merge( $targetArray, $sourceArray);
$array_text = recurse_array($result);
echo $array_text;

function recurse_array($values){
    $content = '';
    if( is_array($values) ){
        foreach($values as $key => $value){
            if( is_array($value) ){
                $content.="$key<br />".recurse_array($value);
            }else{
                $content.="$key = $value<br />";
            }

        }
    }
    return $content;
}

You have to have the same number of elements in both arrays so we start with counting of elements and add necessary NULL values by array_pad

if (count($a1) > count($a2))
{
    $a2 = array_pad1($a2, count($a1), NULL);
}
elseif (count($a1) < count($a2))
{
    $a1 = array_pad($a1, count($a2), NULL);
}

Then we use array_combine, which creates new array. From both arrays we use values by array_values. From first array we use values as keys and from second array we use values as values:-)

$target = array_combine(array_values($a1), array_values($a2))