0

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.

1
  • Regarding concept, you have to be sure that values of initial array are different to avoid key override at the end. Commented Jun 9, 2016 at 20:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.