简体   繁体   中英

How to set keys in a multidimentional array in php

I have doubt in php i want to set an associative array for which i have the keys ,as well as values. i have an array $headers and a mutidimentional array $data as follows:

$headers=(
    [0] => Testcase Name
    [1] => Cell Name
    [2] => Customer
    [3] => Flops
    [4] => Title
    [5] => Status
    [6] => Mfix CCR(open/close)
    [7] => Scenerio-Brief Description
    [8] => Expected Results
    [9] => CCR Status
    [10] => CCR No.
    [11] => Remarks
    [12] => Testcase Path
)

$data=(
    [0] => Array
        (
            [0] => /a/b/c
            [1] =>
            [2] =>
            [3] =>
            [4] =>
            [5] => Done
            [6] => close
            [7] => 2D Elastic with scanformat=parallel
            [8] => No miscompares for both scan and logic tests
            [9] =>
            [10] => 1716280
            [11] =>
            [12] =>
        )

    [1] => Array
        (
            [0] => /x/y/z
            [1] =>
            [2] =>
            [3] =>
            [4] =>
            [5] => Done
            [6] => close
            [7] => 2D Elastic with scanformat=parallel & explicitshifts
            [8] => No miscompares for both scan and logic tests
            [9] =>
            [10] => 1717028
            [11] =>
            [12] =>
        )

    [2] => Array
        (
            [0] => /a/p/q
            [1] =>
            [2] =>
            [3] =>
            [4] =>
            [5] => Done
            [6] =>
            [7] => Error if explicitshifts greater than scan length
            [8] => No miscompares for both scan and logic tests
            [9] =>
            [10] =>
            [11] =>
            [12] =>
        )

    [3] => Array
        (
            [0] => /s/m/p
            [1] =>
            [2] =>
            [3] =>
            [4] =>
            [5] => Done
            [6] =>
            [7] => 2D Elastic + wide 1 Masking with scanformat=parallel
            [8] => No miscompares for both scan and logic tests
            [9] =>
            [10] =>
            [11] =>
            [12] =>
        )

)

I want to set the numeric keys [0]....[12] as the values of $headers array. Means i want to replace [0]....[12] with $header[0]....$headers[12].

Please provide a solution.

Use array_combine :

$dataWithKeys = [];
foreach ($data as $row) {
    $dataWithKeys[] = array_combine($headers, $row);
}
$result = array();
foreach($data as $key => $val){
    $temp = array(); 
    foreach($val as $k => $v){
       $temp[$header[$k]] = $v; 
    }
    $result[] = $temp;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM