dtrvzd1171 2014-08-26 03:02
浏览 45
已采纳

按顺序组合顺序数组和关联数组

How to combine sequential array with associative array in order:

Example:

$sequentialArray = [123, 'Jonh'];
$associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];

mergeArray($sequentialArray, $associativeArray);

Return:

Array
(
    [ID] => 123
    [name] => Jonh
    [lastName] => Wood
)
  • 写回答

2条回答 默认 最新

  • drpsrvu85668 2014-08-26 03:04
    关注

    Consider this:

    <?php
    header('Content-Type: text/plain; charset=utf-8');
    
    $sequentialArray  = [ 123, 'Jonh'];
    $associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
    
    $keys = array_slice(
        array_keys($associativeArray),
        0,
        count($sequentialArray)
    );
    
    print_r(
        array_merge(
            $associativeArray,
            array_combine($keys, $sequentialArray)
        )
    );
    ?>
    

    Output:

    Array
    (
        [ID] => 123
        [name] => Jonh
        [lastName] => Wood
    )
    

    Further reading: Array functions @ php.net.


    UPDv1:

    Here is function:

    <?php
    header('Content-Type: text/plain; charset=utf-8');
    
    $sequentialArray  = [ 123, 'Jonh'];
    $associativeArray = ['ID' => '321', 'name' => 'Paul', 'lastName' => 'Wood'];
    
    function mergeArray($assoc, $seq){
        $keys = array_slice(array_keys($assoc), 0, count($seq));
    
        return array_merge($assoc, array_combine($keys, $seq));
    }
    
    print_r(mergeArray($associativeArray, $sequentialArray));
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding