Skip to content

Instantly share code, notes, and snippets.

@fosron
Last active August 26, 2016 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fosron/eb52dd8301b66dd3ef87839abf45872f to your computer and use it in GitHub Desktop.
Save fosron/eb52dd8301b66dd3ef87839abf45872f to your computer and use it in GitHub Desktop.
Conversion of arrays

#Convert a HTML input 2-dimensional array into an array of keys-values

We get this JSON input:

{
    "number":[
        "1241",
        "1241"
    ],
    "client_instructions":[
        "Test",
        "Test 2"
    ]
}

We need this output:

[
    {
        "number" : "1241",
        "client_instructions" : "Test"
    },
    {
        "number" : "1241",
        "client_instructions" : "Test 2"
    }
]

I came up with this

$output = [];
$keys = array_keys($array);
$i = 0;
do{
    $o = [];
    foreach($keys as $k){
        $o[$k] = $array[$k][$i];
    }
    $output[] = $o;
    $i++;
} while($i < count($array[$keys[0]]));

Could this be done better?

@fosron
Copy link
Author

fosron commented Aug 26, 2016

function flipDiagonally($arr) {
    $out = array();
    foreach ($arr as $key => $subarr) {
        foreach ($subarr as $subkey => $subvalue) {
            $out[$subkey][$key] = $subvalue;
        }
    }
    return $out;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment