基于迭代组合数组并使其成为多维

时间:2016-10-19 01:02:51

标签: php arrays multidimensional-array

所以我有两个数组。我们称它们为member_ids和member_names

所以第一个数组(member_ids)看起来像:

Array
    (
        [0] => 572149922960422
        [1] => 1586735531587728
        [2] => 1084479334908663
        [3] => 9875443331682
        [4] => 9291002010388
        [5] => 2108382717199939
        [6] => 911647002295982
        [7] => 100222991929377
    )

第二个数组(member_names)看起来像

Array
    (
        [0] => John Doe
        [1] => Jane Doe
        [2] => Shawn Smith
        [3] => Jack Nickleson
        [4] => Brad Pitt
        [5] => Chad Kroger
        [6] => Angelina Jolie
        [7] => Bruce Campell
    )

最重要的是,即使变量可以不同,迭代也总是相互匹配(意味着member_id [0]是member_name [0]的成员ID,依此类推)。但是我想创建一个多维的名为member_info,它使用来自两个数组的数据,所以新的URL(如果从两个数组中获取数据)将如下所示:

Array
(
  [0] => Array
    (
        [member_id] => 572149922960422
        [member_name] => John Doe
    )

  [1] => Array
    (
        [member_id] => 1586735531587728
        [member_name] => Jane Doe
    )

  [2] => Array
    (
        [member_id] => 1084479334908663
        [member_name] => Shawn Smith
    )

  [3] => Array
    (
        [member_id] => 9875443331682
        [member_name] => Jack Nickleson
    )

  [4] => Array
    (
        [member_id] => 9291002010388
        [member_name] => Brad Pitt
    )

  [5] => Array
    (
        [member_id] => 2108382717199939
        [member_name] => Chad Kroger
    )

  [6] => Array
    (
        [member_id] => 911647002295982
        [member_name] => Angelina Jolie
    )

  [7] => Array
    (
        [member_id] => 100222991929377
        [member_name] => Bruce Campell
    )

)

请记住两个数组都有所不同,因此两个数组的id和name的变量都取决于数据库。这只是我想要实现的一个例子。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

<?php

$ids = [
    572149922960422,
    1586735531587728,
    1084479334908663,
    9875443331682,
    9291002010388,
    2108382717199939,
    911647002295982,
    100222991929377
];

$names = [
    "John Doe",
    "Jane Doe",
    "Shawn Smith",
    "Jack Nickleson",
    "Brad Pitt",
    "Chad Kroger",
    "Angelina Jolie",
    "Bruce Campell"
];

function customCombine($combined){
    $final = [];
    $i = 0;
    foreach($combined as $id => $name){
        $final[$i]['member_id'] = $id;
        $final[$i]['member_name'] = $name;
        $i++;
    }

    return $final;
}

print_r(customCombine(array_combine($ids,$names)));

您可以看到结果here