简体   繁体   中英

PHP: How do I flip array key/value pairs selectively?

With an array defined as...

    $my_array = array (
        'a' => array( 'BROWN' ),
        'b' => array( 'GREEN', 'MIN_LEN' => 2, 'MAX_LEN' => 60, 'SOMETHING' )
    );

Which looks like...

[a] => Array
    (
        [0] => BROWN
    )

[b] => Array
    (
        [0] => GREEN
        [MIN_LEN] => 2
        [MAX_LEN] => 60
        [1] => SOMETHING
    )

How may I convert it to...

[a] => Array
    (
        [BROWN] => BROWN
    )

[b] => Array
    (
        [GREEN] => GREEN
        [MIN_LEN] => 2
        [MAX_LEN] => 60
        [SOMETHING] => SOMETHING
    )

Notice the keys are the string value instead of numeric. OR it would be acceptable for the values to be null. eg [BROWN] => ''. So far all I can think of is array_flip, but I can't use that selectively.

foreach ($my_array as $oKey => $oVal) {
  foreach ($oVal as $iKey => $iVal) {
    if (!is_string($iKey) && is_string($iVal)) {
      $my_array[$oKey][$iVal] = $iVal;
      unset($my_array[$oKey][$iKey]);
    }
  }
}

See it working

You're going to need a user defined function. Something like:

function selective_flip(&$arr) {
    foreach($arr as &$subarr) { //loops through a and b
        foreach($subarr as $key => $value) {
            if(is_string($value)) {
                $subarr[$value] = $value;
                unset($subarr[$key]);
            }
        }
    }
}

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