将平面数组中的所有值(第一个除外)附加为二维数组的新列

问题描述 投票:0回答:6

这是我的两个数组:

$test = array(
    "0" => array(
        "mem_id" => "299", 
        "profilenam" => "Guys&Dolls", 
        "photo_b_thumb" => "photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg"
    ), 
    "1" => array(
        "mem_id" => "344", 
        "profilenam" => "Dmitry", 
        "photo_b_thumb" => "no")
    );

$distance = array(
    "0" => "0", 
    "1" => "3.362", 
    "2" => "0.23"
);

我想将它们组合为:

Array
(
    [0] => Array
        (
            [mem_id] => 299
            [profilenam] => Guys&Dolls
            [photo_b_thumb] => photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg
            [distance] => 3.362
         )

    [1] => Array
        (
            [mem_id] => 344
            [profilenam] => Dmitry
            [photo_b_thumb] => no
            [distance] => 0.23
        )

)

我尝试了下面的代码,但它不起作用:

foreach ($test as $key => $value) {
    $merged = array_merge((array) $value, $distance);
}
print_r($merged);
php arrays multidimensional-array merging-data
6个回答
2
投票
<?php

    foreach($test as $index=>$array)
    {
         $test[$index]['distance'] = $distance[$index]
    }

    print_r($test);
?>

1
投票
$test = array("0" => array("mem_id" => "299", "profilenam" => "Guys&Dolls", "photo_b_thumb" => "photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg"
    ), "1" => array("mem_id" => "344", "profilenam" => "Dmitry", "photo_b_thumb" => "no"));

$distance = array("0" => "0", "1" => "3.362", "2" => "0.23");

foreach( $test as $id => $data ) {
    $test[$id]['distance'] = $distance[$id];
}

这样的东西应该有效!


1
投票
foreach ($test as $key => &$value) {
  $value["distance"] = $distance[$key];
}

0
投票

我认为array_merge_recursive可以满足你的需要。

编辑:事实并非如此。 :) 但是,它的派生版本(发布在

array_map_recursive
手册页中)似乎确实如此,请参阅 this codepad。我很想知道在大型数据集上哪个更快。


0
投票

之前的所有答案似乎都忽略了这样一个事实:在将两个数组映射在一起时,第一个距离值将被忽略。 使用

array_slice()
省略第一个元素,然后调用
array_map()
同步遍历两个有效负载,并将距离列附加到测试数组的每一行。 演示

var_export(
    array_map(
        fn($row, $d) => $row + ['distance' => $d],
        $test,
        array_slice($distance, 1)
    )
);

输出:

array (
  0 => 
  array (
    'mem_id' => '299',
    'profilenam' => 'Guys&Dolls',
    'photo_b_thumb' => 'photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg',
    'distance' => '3.362',
  ),
  1 => 
  array (
    'mem_id' => '344',
    'profilenam' => 'Dmitry',
    'photo_b_thumb' => 'no',
    'distance' => '0.23',
  ),
)

-1
投票
foreach ($test as &$value)
{
   $value['distance'] = array_shift($distance);
}
© www.soinside.com 2019 - 2024. All rights reserved.