简体   繁体   中英

PHP multidimensional associative array

I am new to php & I'm not sure that this can be done, but I am hoping that someone knows how to. I've collected all the data that I need to submit but now I need to reformat it before I can json_encode to send to the database.

Basically, I have 1 parent array($data) containing 3 sub-arrays ($hours, $WId, $Pid). I need to create associative arrays for each index position & join them together.

Here is my parent array:

$data = array(
'hours' => array(),
'wId' => array(),
'phaseId' => array(),
);

Here is what currently returns when I print_r each of these arrays:

Array ( [hours] => Array ( [0] => 0.5 [1] => 1 [2] => 2 ) ) 
Array ( [wId] => Array ( [0] => 10, [1] => 9, [2] => 8, ) ) 
Array ( [phaseId] => Array ( [0] => 20, [1] => 20, [2] => 19, ) ) 

I need to take these "vertical" arrays & turn them in to "horizontal" arrays per index, using thearray name as the $key & the value for that index as $value. Here is what I need to return.... (Syntax is probably wrong but you can get the idea.)

Array[1] ("hours" => 0.5, "wId" => 10, "phaseId" => 20)
Array[2] ("hours" => 1, "wId" => 9, "phaseId" => 20)
Array[3] ("hours" => 2, "wId" => 8, "phaseId" => 19)

Is there a function that will allow me to do this easily? I saw how to join & merge them together but not sure how to set the array name (hours, etc) as the $key & the value for each index as $value. I need to loop it too because the length of the arrays will vary. (But they will always the same length as each other, so index should still work as what needs to be collected.)

Any suggestions would be greatly appreciated :)

<?php
// set up your output array
$result = array();

// loop through $data, exposing $name for later use
foreach ($data as $name => $array) {

    // loop through each named array and set the desired value
    // using the current $key and $name
    foreach ($array as $key => $value) {
        $result[$key][$name] = $value;
    }
}

// tada!
print_r($result);

NOTE: In your desired results in your question, you had the parent Array keys starting at 1 . This answer assumes that's a typo and you actually wanted them to match the input. If you indeed wanted it to start at one, just change this line in my answer:

$result[$key+1][$name] = $value;

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