0

I need to replace all values in a multidimensional array by their respective key, but only if the value is not an array.

From:

array(
    'key1' => array(
        'key2' => array(
            'key3' => 'val'
        )
    )
);

To:

array(
    'key1' => array(
        'key2' => array(
            'key3'
        )
    )
);

Does anyone know a way to do this nicely?

1 Answer 1

1

This seems to do more or less what you want (fiddle):

<?php
function convert($arr) {
    $ret = array();
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            $ret[$key] = convert($value);
        } else {
            $ret[] = $key;
        }
    }
    return $ret;
}
$test = array(
    'key1' => array(
        'key2' => array(
            'key3' => 'val'
        )
    )
);
var_dump(convert($test));

Output:

array(1) {
  ["key1"]=>
  array(1) {
    ["key2"]=>
    array(1) {
      [0]=>
      string(4) "key3"
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think he needs $ret[] = $key;
Thanks for you answer. I had to make one modification, because I need the key of the last item as the value. see ideone.com/JCoR0f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.