Demo Class
Demo Class

Reputation: 1

Convert multidimensional array with key and value

I have PHP array like:

Array
(
[11] => Array
    (
        [0] => foo
        [1] => bar
        [2] => hello
    )

[14] => Array
    (
        [0] => world
        [1] => love
    )

[22] => Array
    (
        [0] => stack
        [1] => overflow
        [2] => yep
        [3] => man
    )
 )

I want the result as:

array (
 'foo' => '11',
 'bar' => '11',
 'hello' => '11',
 'world' => '14',
 'love' => '14',
 'stack' => '22',
 'overflow' => '22',
 'yep' => '22',
 'man' => '22'
 )

Tried foreach inside foreach but still could not make it that way. There are only two levels.

Upvotes: 0

Views: 322

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

You didn't show your foreach attempt, but it's fairly simple:

foreach($array as $key => $val) {
    foreach($val as $v) {
        $result[$v] = $key;
    }
}

You could wrap the inner foreach in an if(in_array()) if they aren't guaranteed to be arrays. Also, all sub array values must be unique or you'll only get a key/value for the last one.

Here's another way:

$result = array();

foreach($array as $key => $val) {
    $result = array_merge($result,
                array_combine($val, array_fill(0, count($val), $key)));
}

Creates a result array using the values of the inner array as keys and filling the values with the parent array key. Merge with the previous result.

Upvotes: 2

Poiz
Poiz

Reputation: 7617

You can do that easily with a FOREACH Loop as shown below. And by the way, you can as well test it HERE.

    <?php

        $arr        = [
            "11" =>["foo", "bar", "hello"],
            "14" =>["world", "love"],
            "22" =>["stack", "overflow", "yep", "man"],
        ];

        $arrFinal   = array();
        foreach($arr as $intKey=>$subArray){
            if(is_array($subArray)){
                foreach($subArray as $ikey=>$value){
                    $arrFinal[$value] = $intKey;
                }
            }
        }
        var_dump($arrFinal);

RESULT OF VAR_DUMP

        array (size=9)
          'foo' => int 11
          'bar' => int 11
          'hello' => int 11
          'world' => int 14
          'love' => int 14
          'stack' => int 22
          'overflow' => int 22
          'yep' => int 22
          'man' => int 22

Upvotes: 1

Related Questions