组合一个基于迭代的数组,使其成为多维的



我有两个数组。我们称它们为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的变量将取决于数据库。这只是我想要实现的一个例子。

你可以这样做:

<?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)));

您可以在这里看到结果

相关内容

  • 没有找到相关文章

最新更新