Transpose a PHP multidimensional array with predefined keys

前端 未结 2 1570
一向
一向 2021-01-26 19:22

I have a multidimensional array with 3 keys (\"length\", \"width\" and \"height). Each key is associated with an array of values:

$data = [
    \"length\" =>          


        
相关标签:
2条回答
  • 2021-01-26 19:25

    The following function will do the job:

    function transpose($data)
    {
        $result = [];
        $keys = array_keys($data);
        for ($row = 0,  $rows = count(reset($data)); $row < $rows; $row++) {
            foreach ($keys as $key) {
                $result[$row][$key] = $data[$key][$row];
            }
        } 
    
        return $result;
    }
    

    Notice that the function is a general solution it doesn’t depend on the name of the keys nor on the number of entries of each key.

    0 讨论(0)
  • you can try this one to get the arrays like you said

       $height = array(12,44);
    $width = array(20,50);
    $length = array(30,50);
    $new_array[0] = $height[0];
    $new_array[1] = $width[0];
    $new_array[2] = $length[0];
    $new_array2 = $new_array[1];
    print_r($new_array);
    echo "<br>";
    print_r($new_array2);
    
    0 讨论(0)
提交回复
热议问题