1

我有三个数组如下:

Array
(
    [1000] => Item 0
    [1001] => Item 1
    [1002] => Item 2
)

Array
(

    [1000] => £35.00
    [1001] => £60.00
    [1002] => £24.00
)
Array
(
    [1000] => 1
    [1001] => 2
    [1002] => 3
)

我需要合并这三个保留键的数组,如下所示:

Array
(
    [1000] => Array
                (
                    [0] => Item 0
                    [1] => £35.00
                    [2] => 1
                )
    [1001] => Array
                (
                    [0] => Item 1
                    [1] => £60.00
                    [2] => 2
                )
    [1002] => Array
                (
                    [0] => Item 2
                    [1] => £24.00
                    [2] => 3
                )
)

array_map(null, array1, array2, array3)在一定程度上解决了它,但不保留密钥。怎么做到呢?

4

3 回答 3

0

试试这个代码,将一个数组键保存在另一个数组中,并在合并数组后填充键

$array1_keys = array_keys($array1);
$mapped_array = array_map(null, $array1, $array2, $array3);
//now assign original keys
$merged_final_array = array_fill_keys($array1_keys, $mapped_array);

演示

于 2015-01-29T10:01:11.563 回答
0

您可以将您的 array_map 与 array_keys() 与 array_combine() 中的原始数组一起包装

$array1 = array(
    1000 => 'Item 0',
    1001 => 'Item 1',
    1002 => 'Item 2',
);
$array2 = array(
    1000 => '£35.00',
    1001 => '£60.00',
    1002 => '£24.00',
);
$array3 = array(
    1000 => 1,
    1001 => 2,
    1002 => 3,
);

$result = array_combine(
    array_keys($array1),
    array_map(null, $array1, $array2, $array3)
);
var_dump($result);
于 2015-01-29T10:01:28.063 回答
0

我希望这段代码可以帮助你:

$one =Array(    "1000" => "£35.00","1001" => "£60.00","1002" => "£24.00","1003" => "£36.00","1004" => "£80.00","1005" => "£24.00");
$two = array("1000"=>"1","1001"=>"2","1002"=>"3","1003"=>"4","1004"=>"5","1005"=>"6");
$response = array();
foreach(array_keys($one) as $key =>$val)
{
    $response[$val] = array(0=>"item ".$key,1=>$one[$val],2=>$two[$val]);
}
echo "<pre>";print_R($response);
于 2015-01-29T10:12:26.530 回答