PHP using one array as keys for subarray of multidimensional array

Issue

So i got one single dimensional array like:

Array
(
[0] => md5
[1] => name
[2] => description
[3] => url
)

and one multidimensional array:

Array
(
    [0] => Array
        (
            [0] => md5#1
            [1] => name1
            [2] => desc1
            [3] => url1
         )  
    [1] => Array
        (
            [0] => md5#2
            [1] => name2
            [2] => desc2
            [3] => url2
         )  
)

and I want to use values of first array as keys for subarrays of the multidimensional one, so the output should look like:

Array
    (
        [0] => Array
            (
                [md5] => md5#1
                [name] => name1
                [desription] => desc1
                [url] => url1
             )  
        [1] => Array
            (
                [md5] => md5#2
                [name] => name2
                [description] => desc2
                [url] => url2
             )  
    )

Alternatively(as a bit offtopic question), how can I sort the elements of multidimensional array by values of md5 if they keys of subarray are not [md5] but [0]?

Thanks in advance!

Solution

For combining values of two arrays where values of one are keys, and values of other are values, use array_combine function:

$keysArray  = [];
$multiArray = [];
$result_array = [];
foreach ($multiArray as $value) {
    $result_array[] = array_combine($keysArray, $value);
}

For sorting – use usort and define your custom function:

usort($result_array, function($a, $b) { return strcmp($a['md5'], $b['md5']); });

Answered By – u_mulder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published