Anonymous
Anonymous

Reputation: 1094

How to flip Multidimensional array in PHP using array_flip

I have Multidimensional array with key value pair so I want to flip i.e key gets to value place and values get to key place but I am getting error

My Php code is:

echo '<pre>',print_r($res),'</pre>';

output when print_r($res):

Array
(
    [0] => Array
        (
            [userid] => 1
        )

    [1] => Array
        (
            [userid] => 2
        )

    [2] => Array
        (
            [userid] => 3
        )

)

getting error in output when want to flip this array:

array_flip(): Can only flip STRING and INTEGER values!

How to solve this?

Upvotes: 2

Views: 6650

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

You are trying to flip a multidimensional array where each value is an array, but according to the docs of array_flip:

Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.

You could use array_map to use array_flip on each entry:

$a = [
    ["userid" => 1],
    ["userid" => 2],
    ["userid" => 3],
];

$a = array_map("array_flip", $a);

print_r($a);

Result

Array
(
    [0] => Array
        (
            [1] => userid
        )

    [1] => Array
        (
            [2] => userid
        )

    [2] => Array
        (
            [3] => userid
        )

)

See a php demo

Upvotes: 6

Nashir Uddin
Nashir Uddin

Reputation: 748

array_flip() does not flip array as values. array_flip() can only flip string and integer values.

You can try this:

 $arr = [
   [ 'userid' => 1 ],
   [ 'userid' => 2 ],
   [ 'userid' => 3 ]
];
foreach($arr as $a){
    $flipped[] = array_flip($a);
}
print_r($flipped);

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

You can try the following way

$arr = [
   [ 'userid' => 1, ],
   [ 'userid' => 2, ],
   [ 'userid' => 3, ]
];
array_walk($arr, function(&$val) { $val = array_flip($val); });

Upvotes: 0

Related Questions