简体   繁体   中英

How to flip Multidimensional array in PHP using array_flip

I have Multidimensional array with key value pair so I want to flip ie 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?

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, ie 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

You can try the following way

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

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);

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