Josh Holly Josh Holly - 1 month ago 4
PHP Question

Combine an array based on iteration and make it multidimensional

So I have two arrays. Let's call them member_ids and member_names

So the first array (member_ids) could look like:

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


The second array (member_names) could look like

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
)


The most important thing, is that even though the variables can be different, the iterations will always match up with each other (meaning that member_id[0] is the member ID for member_name[0], and so on). But I'd like to create a multidimensional called member_info that uses data from both arrays, so the new URL (if you take data from both the arrays) would look like this:

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
)


)

Keep in mind both arrays vary, so the variables for both the id and name for both arrays will depend on the database. This is just an example of what I'm trying to achieve.

Answer

You could do something like:

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

You can see the results here.