简体   繁体   中英

map array to key value pair in php

I have the following array:

    array (size=2)
      'filename' => 
        array (size=2)
          0 => string 'f1' (length=2)
          1 => string 'f2' (length=2)
      'url' => 
        array (size=2)
          0 => string 'u1' (length=2)
          1 => string 'u2' (length=2)

I want to map it like so:

array (size=2)
  0 => 
    array (size=2)
      'filename' => string 'f1' (length=2)
      'url' => string 'u1' (length=2)
  1 => 
    array (size=2)
      'filename' => string 'f2' (length=2)
      'url' => string 'u2' (length=2)

How would I write such a map without knowing what the keys are called (filename and url). Would it also be possible for larger arrays?

How about this:

foreach ($startArray as $key1 => $value1) {
    foreach ($value1 as $key2 => $value2) {
        $endArray[$key2][$key1] = $value2;
    }
}

This solution will be flexible enough to deal with arrays of any size.

With your array as $startArray:

$result = array();
$counter = 0;
while ( count ( array_values($startArray)[0] ) < $counter - 1 ) {
    $result[] = add_array( $startArray, $counter );
    $counter++;
}
function add_array( $array, $index ) {
    $result = array();
    foreach ( $array as $array_key => $array_value ) {
        $result[$array_key] = $array_value[$index];
    }
    return $result;
}

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