How to create an associative array from two arrays?

A simple foreach solution:

https://3v4l.org/gbBad

<?php

$keyArray = array("clientId", "clientName", "clientAdsress", "clientPhone");
$valuesArray = array(
    "0" => array("1001", "aaaaa", "ddddddd", "22222222"),
    "1" => array("1002", "bbbbbb", "ddddddd", "11111111"),
    "2" => array("1003", "ccccc", "ddddddd", "33333333")
);
$expected = array(
    "clientId" => array("1001", "1002", "1003"),
    "clientName" => array("aaaaa", "bbbbbb", "ccccc"),
    "clientAdsress" => array("ddddddd", "ddddddd", "ddddddd"),
    "clientPhone" => array("22222222", "11111111", "33333333")
);

$result = [];
foreach ($keyArray as $key => $keyName) {
    foreach ($valuesArray as $value) {
        $result[$keyName][] = $value[$key];
    }
}

var_dump($result === $expected);

Output for 7.1.25 - 7.3.2

bool(true)


One way to do it is with array_combine and array_column:

$finalData = array_combine($keyArray, array(array_column($valuesArray, 0),
                                            array_column($valuesArray, 1),
                                            array_column($valuesArray, 2),
                                            array_column($valuesArray, 3)));
print_r($finalData);

Output:

Array ( 
    [clientId] => Array ( [0] => 1001 [1] => 1002 [2] => 1003 )
    [clientName] => Array ( [0] => aaaaa [1] => bbbbbb [2] => ccccc )
    [clientAdsress] => Array ( [0] => ddddddd [1] => ddddddd [2] => ddddddd )
    [clientPhone] => Array ( [0] => 22222222 [1] => 11111111 [2] => 33333333 ) 
)

Demo on 3v4l.org

Tags:

Php

Arrays