3

I have 2 arrays:

array 1 I want it to be a keys(duplicate is ok) in array_combine:

Array
    (
        [0] => id
        [1] => user_id
        [2] => firstname
    )

And here's my array 2 that I wanted to be the values in array_combine:

Array
    (
        [0] => 363
        [1] => 363
        [2] => Omotayo
    )

Array
    (
        [0] => 167
        [1] => 167
        [2] => Shafraaz
    )

Now challenge is, I have 2 arrays the first one has only one array and the second array has 2 inside arrays. The first array that I wanted to be the keys(duplicate) in array_combine. My desire output like below:

    Array
    (
        [id] => 363
        [user_id] => 363
        [firstname] => Omotayo
    )
    Array
    (
        [id] => 167
        [user_id] => 167
        [firstname] => Shafraaz
    )

Just wonder is there way to achieve this task? Appreciated any advise!!

Thanks

SonDang
  • 1,468
  • 1
  • 15
  • 21

2 Answers2

3

Why not just run array_combine on each inner array of $array2?

$final = array();
foreach($array2 as $array) {
    $final[] = array_combine($array1, $array);
}

This'll leave $final as the expected array with proper key/value pairs.

MasterOdin
  • 7,117
  • 1
  • 20
  • 35
  • I have tried it before, and it threw an errors: Warning: array_combine(): Both parameters should have an equal number of elements – SonDang Jul 03 '15 at 03:19
  • What's the exact values of your variables? Like $array1 = ..., $array2 = ..., etc as the only reason you'd get that reason based on your question is if you were iterating over the individual elements of $array2 instead of each outer array maybe? – MasterOdin Jul 03 '15 at 03:23
  • below are my 2 arrays $array1 = Array( id, user_id, firstname ) $array2 = Array([0] => array('363', '363', 'Omotayo'), [1] =>array('167', '167', 'Shafraaz')) – SonDang Jul 03 '15 at 03:27
  • very strange, it fails in my environment with the loop :/ – SonDang Jul 03 '15 at 04:01
  • My PHP Version is 5.5.12. Were this a problem? – SonDang Jul 03 '15 at 04:09
  • Just tested against 5.5.24. At this point, I'm out of ideas and if the exact code I posted in the ideone link isn't working in your environment, sounds like your environment is somehow borked. – MasterOdin Jul 03 '15 at 04:12
1

Please, test this method and see if it works on your environment:

$keys = array("id","user_id","firstname");
$values = array(
    array(363,363,"Omotayo"),
    array(167,167,"Shafraaz")
);
$out = array();
foreach($values as $ukey=>$user)
{
    foreach($user as $key=>$data)
    {
        $values[$ukey][$keys[$key]] = $data;
        unset($values[$ukey][$key]);
    }
}
print_r($values);
GGG
  • 640
  • 1
  • 9
  • 27